javascript - 对象可能是查找函数方法中的“未定义”打字稿
问题描述
我真的不知道如何捕获错误。有人可以帮我吗?
如果您有更好的解决方案(如果看起来更好,那也很棒)
interface Props {
prevCases: Array<Case>
}
export function MyFunction(props) {
const { prevCases } = this.props;
const myType = prevCases << Object is possibly 'undefined'.
.find((case: Case) => case?.id === myId).resultItems
?.find((item: Item) => item.name === myPath)
?.type;
console.log(ArrayA[myType]); << Type 'undefined' cannot be used as an index type.
...
解决方案
尝试使用简化/可读的代码,以便读者能够理解。1个问题是你不能写 this.prop 这会寻找全局变量,只用 prop 替换它。使用 try catch 块调试进一步的问题
interface Props {
prevCases: any[]
}
let myId = 1;
let myPath = 'abc';
function MyFunction(props : any[]) {
try {
const myType = props.filter(prop => prop ? prop['id'] === myId : false)
.filter(prop => prop ? prop['name'] === myPath : false);
myType.forEach(item => console.log(item['value']));
}
catch(Error){
console.log(Error.message);
}
}
MyFunction([null,{'id':2,'name':'abc','value':'b'},{'id':1,'name':'abc','value':'c'}]);
推荐阅读
- c# - System.InvalidOperationException:“由于缺少功能而跳过了所有实例。” 错误来自数据集还是代码?
- node.js - TS:错误:找不到模块(修改 tsconfig 没有帮助)
- python - 计算索引的 Pandas df timedelta
- android - 共享 CoroutineExecutorExtension 的定义
- pytorch - 将具有非零操作的 Pytorch 模型转换为 TensorRT
- javascript - 为什么 css font-weight 属性在我的情况下不起作用?
- r - 识别一列中的字符串共享的数据框中的值
- python - 内联评论 ruamel.yaml
- html - Material-UI 水平居中网格项目
- amazon-dynamodb - PynamoDB - 索引未找到元素