Home > front end >  Can't infer object type from object property
Can't infer object type from object property

Time:11-06

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?

CodePudding user response:

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

  • Related