跨多个模块的TypeScript模块扩充
我试图修改另一个模块内的对象的原型(类似于这里所示 )。 但是,模块扩充似乎只在增加在同一模块中的所需文件中声明的对象而不是另一个模块时才起作用。
例如,我有一个类, TestClass
:
// some-module/TestClass.ts export class TestClass { someValue: string = "hi"; someFunc(): number { return 5; } }
在同一个模块中,我有这个:
// some-module/index.ts import { TestClass } from "./TestClass"; declare module "./TestClass" { interface TestClass { doSomethingElse(): void; } } TestClass.prototype.doSomethingElse = function(): void { console.log("Something else"); };
这工作正常。 但是,如果我将TestClass
移动到另一个模块( test-module/TestClass.ts
)并像这样适当地修改代码,它会给我提供错误'TestClass' only refers to a type, but being used as a value here.
每当我尝试访问TestClass
。
// some-module/index.ts import { TestClass } from "test-project"; declare module "test-project" { interface TestClass { doSomethingElse(): void; } } TestClass.prototype.doSomethingElse = function(): void { console.log("Something else"); };
我正在使用CommonJS使用NodeJS模块parsing。
任何帮助将非常感激。
这是因为您需要导入整个模块导入*,而不是只需要您需要的类,请参阅https://github.com/Microsoft/TypeScript/issues/9015