解决 VSCode 错误和 Typescript 4.4+ 差异
Resolve VSCode Errors and Typescript 4.4+ Discrepancy
Typescript 4.4 引入了 useUnknownInCatchVariables
选项,当 tsconfig 启用 strict
时默认启用。该选项将 catch 中 e 的类型从 any 更改为 unknown。考虑以下代码:
// index.ts
function example() {
try {
throw new Error('Foo')
} catch (e) {
console.log(e.stack)
}
}
example()
VSCode 认为上面的代码是有效的,并且在突出显示时看起来像下面的代码(注意它如何将 e 视为 any 类型):
没有突出显示的错误。然而 tsc 生成:
index.ts:5:17 - error TS2571: Object is of type 'unknown'.
32 console.log(e.stack);
我的 tsconfig:
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "build",
"sourceMap": true
},
"include": ["index.ts"],
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Recommended"
}
如何在 VSCode 中看到错误时解决此不一致问题并利用新的 useUnknownInCatchVariables
?
经过一番折腾,最终变得简单了。之前没有考虑过,但是更新 VSCode 到最新版本解决了这个问题。
Typescript 4.4 引入了 useUnknownInCatchVariables
选项,当 tsconfig 启用 strict
时默认启用。该选项将 catch 中 e 的类型从 any 更改为 unknown。考虑以下代码:
// index.ts
function example() {
try {
throw new Error('Foo')
} catch (e) {
console.log(e.stack)
}
}
example()
VSCode 认为上面的代码是有效的,并且在突出显示时看起来像下面的代码(注意它如何将 e 视为 any 类型):
没有突出显示的错误。然而 tsc 生成:
index.ts:5:17 - error TS2571: Object is of type 'unknown'.
32 console.log(e.stack);
我的 tsconfig:
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "build",
"sourceMap": true
},
"include": ["index.ts"],
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Recommended"
}
如何在 VSCode 中看到错误时解决此不一致问题并利用新的 useUnknownInCatchVariables
?
经过一番折腾,最终变得简单了。之前没有考虑过,但是更新 VSCode 到最新版本解决了这个问题。