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

TypeScript infer returns a strange type

enter image description here

type FromProps<T> = T extends AA<infer E> ? true : false;

class AA<E> {}

class CC {}

class BB {
  aa: AA<string> = new AA
  bb: CC = new CC
}

function get<K extends keyof BB>(a: K): FromProps<BB[K]> {
  return null as unknown as FromProps<BB[K]>
}

let c = get("bb"); // true

Why is the type of c not false but true ???

Typescript Playground

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 :

Your 2 classes AA and CC are assignable to each other – both have no properties so for the typescript compiler, they’re interchangable.

If you want them to be unique, you have to add at least one unique property to each of them:

type FromProps<T> = T extends AA<infer E> ? true : false;

class AA<E> {
  public id: number = 0;
}

class CC {
  public name: string = 'Mike';
}

class BB {
  aa: AA<string> = new AA
  bb: CC = new CC
}

function get<K extends keyof BB>(a: K): FromProps<BB[K]> {
  return null as unknown as FromProps<BB[K]>
}

let c = get("bb"); // false

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