首页 > 解决方案 > 模块扩充不需要导入?

问题描述

我有一个这样的模块:

// 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 is not a function。因为我没有将modules/run.ts导入modules/index.ts。

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

非常感谢!

标签: typescript

解决方案


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


推荐阅读