【问题标题】:Module augmentation error :'x' only refers to a type, but is being used as a value here模块扩充错误:'x' 仅指一种类型,但在此处用作值
【发布时间】:2017-12-03 01:06:42
【问题描述】:

我对此有些陌生。所以,如果我弄错了,请原谅我。 我试图这样做是为了在量角器 ElementFinder 类原型上定义一个方法。

我在这里遵循合并拉取请求中的语法。https://github.com/Microsoft/TypeScript/pull/6213

> 1 import { ElementFinder} from "protractor";
> 2 
> 3 declare module "protractor" {
> 4   interface ElementFinder {
> 5        doSomething(): void;
> 6    } }
> 7
> 8
> 9  ElementFinder.prototype.doSomething = function (): void {
> 10    console.log(""); 
> 11 };

我在第 9 行收到此错误

[ts] 'ElementFinder' 仅指一种类型,但被用作 这里的值。

我在这里做错了什么?示例中唯一不同的是,我使用的是来自 npm 的模块,而不是在我的包中定义的模块。难道不能以这种方式扩充模块吗?

【问题讨论】:

    标签: angular typescript protractor


    【解决方案1】:

    看起来ElementFinder 被键入为interface 而不是class。似乎没有名为 ElementFinder 的导出对象,您可以参考以获取其原型。 protractor 是否在运行时为您提供ElementFinder 构造函数?如果是这样,您可以这样输入:

    type Constructor<T> = {
        new (...args: any[]): T;
        readonly prototype: T;
    }
    declare module "protractor" {
      interface ElementFinder {
        doSomething(): void;
      }
      export const ElementFinder: Constructor<ElementFinder>;
    }
    

    应该修复类型错误,但要确保在运行时确实有一个ElementFinder 构造函数,否则它会在你运行时爆炸。

    【讨论】:

    • 这对我不起作用,我在您的 export const 行上得到 Cannot redeclare block-scoped variable 'Object3D'.(其中 Object3D 是我要扩展的类名)。
    • 我需要先看到您的问题的minimal reproducible example,然后才能提出任何建议。从表面上看,这个问题及其答案不适用于您的情况,因为编译器已经在范围内看到了一个名为 Object3D 的变量;上述问题和答案存在编译器没有任何此类变量的问题。祝你好运!
    • 谢谢,原来是github.com/microsoft/TypeScript/issues/18877 - 我来到这里是因为我在尝试export const 之前看到的错误与 OP 相同 - 即使在我的情况下原因是编译器错误: (
    猜你喜欢
    • 2018-12-30
    • 2018-08-07
    • 2017-12-03
    • 2020-04-28
    • 2021-08-23
    • 2020-12-05
    • 2018-03-31
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多