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 ternary operator breaks identity type

Why is my SupposedId type below not a type identity?

Typescript is complaining that Type 'T' is not assignable to type 'SupposedId<T>'.

How comes T cannot be assignable to either T or T, what am I missing?

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

type SupposedId<T> = T extends object ? T : T;

function makeId<T>(test: T): SupposedId<T> {
  return test // <- Type 'T' is not assignable to type 'SupposedId<T>'
}

Playground example

>Solution :

This is because of distributed conditional types. SupposedId distributes to T extends any | T extends object. Yours is certainly a novel case, since they both actually resolve to T, but the conditional type performs different narrowing based on whether or not T extends object.

However, per the documentation, you can fix it by adding square brackets around each side of the extends keyword:

type SupposedId<T> = [T] extends [object] ? T : T;

function makeId<T>(test: T): SupposedId<T> {
  /* `test` is now one of `T extends object` or `T extends any`,
     not `T extends object | T extends any` */
  return test;
}
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