prmph
prmph

Reputation: 8196

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.

Upvotes: 1

Views: 165

Answers (1)

Taxel
Taxel

Reputation: 4207

You can achieve this this with a custom type predicate

It could look like this.

const element = {} as { type: string, props: Object } | { type: Function, props: any }

function isStringType(obj: { type: string, props: Object } | { type: Function, props: any }): obj is { type: string, props: Object } {
  return typeof obj.type === "string";
}

if (isStringType(element)) {
    element // typed as { type: string;  props: Object;}
}
else {
    element // typed as { type: Function; props: any;}
}

Upvotes: 1

Related Questions