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

Does the never type in TypeScript have specific behaviour when used as a type parameter?

Lets’ have two types

type Type1<T> = T extends never ? { type: "A" } : { type: "B", value: T }
type Type2 = never extends never ? { type: "A" } : { type: "B", value: never }

I would expect that Type1<never> = Type2 but TypeScript thinks otherwise.

When I define two constants with the seemingly same types and assign them the same values

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

const var1: Type1<never> = {
    type: "A",
}

const var2: Type2 = {
    type: "A",
}

then the second constant is accepted by TypeScript but the first one is reported as an error: TypeScript states that the type of var1 is never and cannot be assigned a value.

TypeScript version is 4.9.5

What am I missing?

>Solution :

I think when a generic is given before extends typescript distributes it and since never is an empty union Type1 resolves to never. But in Type2 never is not distributed so it extends never.

https://github.com/microsoft/TypeScript/issues/31751

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