After the introduction of the never type in TS2.0, the operation of the type type is more flexible.

Difference from void

Normally we would define a function with no return value like this:

fun: (a)= > void; 
Copy the code

But in TS void contains at least the following subtypes:

  • undefined
  • null

For example:

// strictNullChecks = false
const v: void / / equivalent to undefined | null

// strictNullChecks = true
const v: void // is equivalent to undefined
Copy the code

No return value at all

Never is a type that returns no value at all, only in one case: code blocking.

Return process.exit(1); while(true){}

function error(message: string) :never {
    throw new Error(message);
}
Copy the code

If a function returns a value of type never, the function must fail to execute completely and break.

Subtypes of all types

Never is a subtype of all types, so it can be interpreted as: all functions return values that contain never:

function fun(s: string) :number {
  if (s == 'a') return 1;
  if (s == 'b') return 2;
  throw new Error;
}
/ / equal fun (s: string) : number | never
Copy the code

Anything not declared as never alone is explicitly displayed, so the following declarations ignore never:

type Temp = 1 | 'a' | never
/ / get
// type Temp = 1 | 'a'

Type ne = never
/ / get
// type ne = never
Copy the code

Used with function types

When we looked at TypeScript’s extends condition type earlier, we encapsulated the Filter

function type using the return value of never:
,>

type Filter<T, U> = T extends U ? never : T;

type Values = Filter<"x" | "y" | "z"."x">;
/ / get the type Values = "y" | "z"
Copy the code

Once you understand these types, it’s very easy to understand the advanced types that are officially expected (e.g., Exclude

, Extract

, NonNullable

).

,>
,>