Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't infer object type from object property

In this code:

type Type1 = { value: string; test: number };
type Type2 = { value: [string]; test: boolean };
type MyType = Type1 | Type2;
let test = (x: MyType) => {
  if (typeof x.value === "string") {
    console.log(x.value, typeof x.test);
    return;
  }
};

if you hover over x.test it says the type is number | boolean.
Why can’t it deduce that it is of type number actually? Doesn’t the if statement guarantee that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to use a type predicate. This specific use case is actually tracked in a GitHub issue yet to be resolved. TypeScript as of now only knows that the child object is that certain type, but it doesn’t bother to infer the parent object:

type Type1 = { value: string; test: number };
type Type2 = { value: [string]; test: boolean };
type MyType = Type1 | Type2;

function isType1(x: MyType): x is Type1 {
  return typeof x.value === "string";
}

let test = (x: MyType) => {
  if (isType1(x)) {
    console.log(x.value, typeof x.test);
    return;
  }
};

test({ value: "hi", test: 2 })

Typescript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading