TypeScript中this类型编译时可推断但编辑时IntelliSense无报错
TypeScript编译报错但VS2019编辑阶段IntelliSense未提示类型错误
问题场景
编译时变量me的类型可被正确推断,因此me.text = num会触发类型错误:Type 'number' is not assignable to type 'string',但在Visual Studio 2019的编辑阶段,IntelliSense并未实时报告该错误。
相关代码
function foo(): void { let x = { text: <string>null, setValue: function(num: number): void { let me = this; me.text = num; // 预期此处触发错误 } }; }
对应的tsconfig配置
{ "compilerOptions": { "target": "ES2015", "lib": [ "DOM", "ES6", "DOM.Iterable", "ScriptHost", "ES2017.String", "ES2018.AsyncIterable" ], "module": "none", "noImplicitAny": false, "noImplicitThis": true, "alwaysStrict": false, "strictNullChecks": false, "strictFunctionTypes": false // 其他配置项 }, "typeAcquisition": { "enable": false // 其他配置项 } }
可行的解决方向
- 更新VS2019及TypeScript插件:VS2019旧版本可能存在IntelliSense对
this类型推断的bug,尝试更新到最新可用的VS2019版本,同时确保TypeScript SDK和插件为最新状态。 - 显式指定
this类型:在函数参数中声明this的具体类型,消除推断歧义,编辑阶段即可触发错误提示:setValue: function(this: { text: string }, num: number): void { let me = this; me.text = num; } - 重置IntelliSense缓存:通过VS2019的命令面板(
Ctrl+Shift+P)执行TypeScript: Restart TS Server或Developer: Reload Window,清理缓存后重新加载项目。 - 调整严格检查配置:尝试开启
strict: true(或单独开启strictThisBindingChecks),提升IntelliSense的类型推断精度,需注意这会启用更严格的全局类型检查,需评估项目兼容性。
内容的提问来源于stack exchange,提问作者JBress
相关产品推荐
相关产品推荐

