首页 > 解决方案 > 对象可能是查找函数方法中的“未定义”打字稿

问题描述

我真的不知道如何捕获错误。有人可以帮我吗?

如果您有更好的解决方案(如果看起来更好,那也很棒)

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.
...

标签: javascripttypescript

解决方案


尝试使用简化/可读的代码,以便读者能够理解。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'}]);

推荐阅读