How does conditional type work in TypeScript

68 Views Asked by At

I came across conditional type in TypeScript and I found many vague definitions about its functionality in TypeScript.

Consider following conditional type as an example:

type NonNullable<T> = T extends null | undefined ? never : T

let MyType : NonNullable<string | null>;

This post is the first result when I search for condition type in TypeScript on google.

It defines T extends U ? X : Y conditional type as follows:

In human language, this conditional type reads as follows: If the type T is assignable to the type U, select the type X; otherwise, select the type Y.

So applying this definition to our example I can say is (string | null) assignable to null type? The answer is no so MyType should be (string | null). Which is wrong

The other post here defines it as follows which makes sense:

Conditional types let you filter out particular members of a union type.

In this definition compiler checks for each possible type(lets call it TT) in union type T, if this type(TT) is assignable to null or undefined compiler filter them out in making definition for MyType.

These are my questions:

  1. Which definition is correct?
  2. Is there any better (and general) definition for conditional types in TypeScript?
0

There are 0 best solutions below