如何解决Typescript 和 Linter 如何解决和决定消息后的最佳打字:变量在分配之前设置?
这是可能出现的常见行为 定义了一个变量,然后是一个 try catch 块
let myVar:TYPEX;
try{
myVar = { build: "the object"}
// useTheObjectTypeX expects myVar obj to be of TYPEX
ExternalLibrary.useTheObjectTYPEX(myVar);
}catch(error){
console.log(error);
// to inspect and info what was the state of the var before the exception
console.log(myVar);
// the above will be mark from the linter as a problem like " Var was used before being assigned"
}
一个选项可以是:
let myVar:TYPEX | Object = {};
try{
myVar = { build: "the object"}
// but here there's the need to typecast to TYPEX or useTheObjectTYPEX and linter will complain it might be of type Object (not accepted by ExternalLibrary )
ExternalLibrary.useTheObjectTYPEX(myVar as TYPEX);
}catch(error){
console.log(error);
// to inspect and info what was the state of the var before the exception
console.log(myVar);
// the above will not complain anymore because of the init to {}
}
您如何看待上述解决方案? 有没有更好的方法来解决这个问题,更优雅/干净?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。