Typescript incorrectly assumes that an element ‘could be’ undefined

  Kiến thức lập trình

Suppose the following:

interface HandleMapDefaultProps {
    item: {
        id: number
    } & Record<string, unknown>;
    renderCustomComponent?: never;
}

interface HandleMapCustomProps {
    renderCustomComponent: () => HTMLElement;
    item?: never;
}

type HandleMapProps = MapDefaultProps | MapCustomProps;
const handleMap = ({
    item,
    renderCustomComponent
} : MapProps): HTMLElement => renderCustomComponent?.() ?? <div>{item.id}</div>

This throws an error,

'item' is possibly 'undefined'

However according to the type provided for props (MapProps), if renderCustomComponent is undefined, then item will always be defined.

Doing item!.id fixes this, but I’m wondering if there’s a better way?

LEAVE A COMMENT