【发布时间】:2019-08-08 09:26:20
【问题描述】:
以下 Typescript 代码在 catch 语句中导致编译错误 ts(2454): Variable "timeout" is used before it has been assigned。
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');
}
什么是满足编译器的好方法?
另见问题Common pattern when variable is used before being assigned
【问题讨论】:
-
在 try 块之外获取 setTimeout :)
-
@Icepickle 这确实可以解决问题,但我的代码有点复杂。
setTimeout实际上是在另一个回调中调用的。见上文!
标签: node.js typescript