以下Typescript代码ts(2454): Variable "timeout" is used before it has been assigned
在catch语句中导致编译错误。
let timeout: NodeJS.Timeout
try {
prepareConnection(() => {
timeout = setTimeout(() => {
console.log('timeout while opening connection');
}, 10000);
openConnection();
});
} catch (err) {
if (timeout) clearTimeout(timeout); //<-- Error ts(2454)
console.error('error while opening connection');
}
有什么好的方法可以使编译器满意?
另请参阅问题在分配变量之前使用变量时的通用模式
我认为最好的解决方案是使用“确定分配声明”(自打字稿2.7起可用)。
确定分配断言是允许!的功能。放置在实例属性和变量声明之后,以中继到TypeScript,即使TypeScript的分析无法检测到该变量的确是出于所有意图和目的而分配的。
let timeout!: NodeJS.Timeout //add a exclamation mark "!"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句