typescript - 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 {}
}
您如何看待上述解决方案?有没有更好的方法来解决这个问题,更优雅/更干净?
解决方案
推荐阅读
- python - 如何在程序运行时读取python中的输出
- android - 如何使用间隔为 5 分钟的 Android WorkManager 安排定期任务
- c# - 如何返回列表
在 grpc 中 - node.js - 在 Debug Container 中安装 Node 依赖项
- flutter - 我正在尝试提供程序,它使一切都很好,但是我的文本小部件中的 textField 文本没有更新
- apache-flink - Flink 中的处理流
- tensorflow-federated - Tensorflow federated:如何将远程工作人员与 iterative_process.next 中的远程数据集映射?
- python - 重复数组直到一定长度
- angular - 无法从角度的 ng-bootstrap lib 中获取属性值
- java - 使用 docker 启动 quarkus 时,错误 OIDC 服务器在 'quarkus.oidc.auth-server-url' URL 不可用