Advanced TypeScript: Unions With Never
Welcome to the Unions With Never lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
TypeScript lets us union a type with
never, but it has no effect. For example,number | neveris justnumber, andstring | neveris juststring.>
function returnStringOrNever(): string | never {return 'Amir';}const name2: string = returnStringOrNever();name2;Result:
'Amir'
>
function returnNumberOrNever(): number | never {return 1;}const n: number = returnNumberOrNever();n;Result:
1
This makes sense if we think about what the
nevertype actually means. Anevermeans "this can never actually have a value at runtime."The type
number | nevermeans "it's either a number, or (a thing that can never actually have a value at runtime)". If theneverpart can never have a value, then there's no need for it to be part of the union. The TypeScript compiler knows that it can discard that possibility. It's kind of like hown + 0is always justn, no matter what valuenhas.This may remind you of something that we saw in an earlier lesson: if types
XandYdon't share any possible values, thenX&Ygives usnever.These are two separate rules about
never. First, impossible intersections give us the typenever. Second,nevercan be removed from any union.On their own, unions with
neveraren't useful. For now, the only thing to know is that theneverpart of a union is always thrown away. However, in future lessons on more advanced types, unions withneverare going to become very important!