首页 > 解决方案 > 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 {}
}


您如何看待上述解决方案?有没有更好的方法来解决这个问题,更优雅/更干净?

标签: typescriptcastinglinter

解决方案


推荐阅读