为什么下面的例子this有一个类型?any
const x = {
name: 'x',
getX() {
// this почему то any
this.name;
},
};
该项目是通过nest cli生成的nest new
封装版本:
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"paths": {
"@/*": ["./src/*"]
}
}
}
答案是针对那些使用 Microsoft 代码编辑器 (IDE) 的人:
有一种在其他代码编辑器/IDE中
this不会有的感觉。any我将感谢那些在其他 IDE(JetBrains 的 WebStorm、IntelliJ IDEA)上检查它的人。您必须设置"strict": true选项。
我找不到任何提及此选项对
this从代码上下文进行类型推断的影响的信息,因此我倾向于相信此问题不会在所有代码编辑器中发生,并且与打字稿编译器设置无关。