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 is not a function。因为我没有将modules/run.ts导入modules/index.ts。
我的问题是,为什么 TypeScript 的编译器应该让 'cat.run()' 在 modules/run.ts 没有导入到 modules/index.ts 时通过编译?
非常感谢!
解决方案
当您有多个输出文件时,TypeScript 编译器不会尝试跟踪以什么顺序加载哪些文件以捕获此类错误。(它确实捕获了在同一个输出文件中定义之前使用某些东西的简单情况。)我的理解是这是因为会有太多误报错误,特别是当您编译其他代码将加载的文件库时一个未知的顺序。
推荐阅读
- constructor - Kotlin 数据类便利构造函数
- angular - “订阅”类型上不存在属性“订阅”
- apache-spark - 如何使用 case when 语句计算 spark sql 中的空白单元格?
- fitnesse - 每个脚本标签的 Fitnesse 固定装置的相同实例
- python-3.x - 使用python在svg文件中使用十六进制更改rgb百分比颜色值
- java - android studio_firebase_storage_获取下载地址
- c# - 如何处理firebase短动态链接Onsuccess结果
- node.js - 将现有 NodeJS 项目转换为 TypeScript 时如何强制将所有文件视为模块
- sql - 通过 updated_at 和 creatd_at 之间的差异的活动记录子集
- sql-server - 可以在 SQL Server 中没有相应的 BEGIN TRAN 的情况下提交事务吗?