简体   繁体   中英

Object is possibly 'undefined' Typescript in find function method

I really don't know how I can capture the error. Could someone help me on this?

If you have better solution (If anything looks better, it's also great)

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

Try to use simplified/readable code, so readers could understand. 1 issue is you cannot write this.prop this looks for global variable, replace that by just prop. Debug further issue by using try catch block

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'}]);

When using object destructuring, the property value can potentially be undefined :

const { prevCases } = this.props;

is the same as:

const prevCases = this.props.prevCases;

and Typescript doesn't know the type of props , so it doesn't know that the property prevCases exist, you need to explicitely tell Typescript that the props argument is of type Props . To do that, you need to declare the type in the function declaration as such:

export function MyFunction(props: Props) {
 // Your function body
}

and that way, Typescript will be use that no matter what happens, the props parameter will always be of type Props

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM