模块增强不需要导入吗?

时间:2018-09-01 15:27:56

标签: typescript

我有一个像这样的模块:

// File: modules/cat.ts
export class Cat {
    greet(): void { console.log('hi...'); }
}

然后我像这样扩展该模块:

// File: modules/run.ts
import {Cat} from './cat';

declare module './cat' {
    interface Cat {
        run();
    }
}

Cat.prototype.run = function() {
    console.log('I can run..');
}

然后我尝试使用这两个模块:

// File: modules/index.ts
import {Cat} from './cat';
// ./run is not imported

let cat = new Cat();
cat.greet(); // Print 'hi...'
cat.run(); // Should not this line cause an error? 

以下是我的tsconfig.json:

{
    "compilerOptions": {
        "sourceMap": true,
        "module": "commonjs",
        "moduleResolution": "node"
    }
}

以上所有代码均可成功编译。但是,当然,当我运行'node modules / index.js'时,出现了一个错误:cat.run不是一个函数。因为我没有将模块/run.ts导入模块/index.ts。

我的问题是,当modules / run.ts没有导入到modules / index.ts中时,为什么TypeScript的编译器应该让'cat.run()'通过编译?

非常感谢您!

1 个答案:

答案 0 :(得分:0)

当您有多个输出文件时,TypeScript编译器不会尝试跟踪以什么顺序加载哪些文件以捕获此类错误。 (它确实捕获了在同一个输出文件中定义某些内容之前使用某些东西的简单情况。)我的理解是,这将导致过多的误报错误,尤其是当您正在编译将要加载其他代码的文件库时订单不明。

相关问题