这是这个问题的存储库,如果你愿意,你可以克隆该存储库,使用 TypeScript 编译,然后在节点中运行它以查看是否存在运行时错误,但没有编译时错误。
切入正题:为什么当我尝试运行从另一个模块文件 2 导入的对象的方法时,为什么我在 file1 中没有收到 TypeScript 的编译时错误,因为该对象没有方法?
这是代码,基本上:
要设置项目:
mkdir test
cd test
npm init --yes
yarn add typescript
touch tsconfig.json
touch index.ts
touch jsModule.js
这是tsconfig.json
:
{
"compilerOptions": {
"allowJs": false,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"module": "es2015",
"moduleResolution": "node",
"noImplicitAny": false,
"noImplicitReturns": true,
"noImplicitThis": true,
"sourceMap": true,
"target": "es2015",
"skipLibCheck": true,
"strict": true,
"resolveJsonModule": true
},
"exclude": ["node_modules"]
}
以下是我创建的两个文件:
// jsModule.js
export const MyModuleObject = {};
// index.ts
import { MyModuleObject } from './jsModule';
console.log(MyModuleObject.method());
问题:打字稿没有说我打电话给MyModuleObject.method()
tsconfig.json
中的"noImplicitAny": false
会导致您的问题。
它只是意味着"允许隐式任何"。由于 TS 对从jsModule.js
导出的内容一无所知,因此实际上允许 TS 将any
指定为该模块的类型。MyModuleObject.method()
变成any.any()
,这很好。
设置"noImplicitAny": true
,则 TS 会投诉。