gCardinal gCardinal - 17 days ago 78
TypeScript Question

Object is possibly 'undefined' in ternary operation

I have this bit of code:

const newProps = {
onClick: props.onSelect ? () => props.onSelect(choice.value) : undefined,
}


Which in TypeScript will give me the error
Object is possibly 'undefined'
.

I thought TypeScript was smart about this and would understand that at this point, props.onSelect can't be undefined. I know about the
!
operator, but I'd like to know why this isn't working.

Answer Source

The problem is that the usage of props.onSelect is in another function, the arrow function you are defining after the ?. This means the compiler cannot guarantee that props.onSelect is not undefined at the time of the call:

Ex:

propsOther.onSelect = undefined;
props.onClick();

You need to check onSelect within the arrow function as well:

const props = {
    onClick: propsOther.onSelect ? () => propsOther.onSelect && propsOther.onSelect(choice.value) : undefined,
}

Note: I assumed you simplified and that there are actually 2 prop objects, because otherwise your code would not compile.