lundi 6 septembre 2021

Simple type narrowing in if statement fails in Typescript

Consider this snippet:

const element = {} as { type: string, props: Object } | { type: Function, props: any }
if (typeof element.type === "string") {
    element
}
else {
    element
}

In both branches of the if statement, the type of element is inferred to be:

{
    type: string;
    props: Object;
} | {
    type: Function;
    props: any;
}

I would have expected that in the first branch of the if statement, the type of element would be { type: string; props: Object; }, and in the second branch, it would be { type: Function; props: any; }

I'm not sure why such basic type narrowing fails.

Aucun commentaire:

Enregistrer un commentaire