TypeScriptBasic types
never
The type of a value that never occurs: functions that don’t end normally, and impossible cases.
Example
#TypeScript
type Shape = { kind: 'circle'; r: number } | { kind: 'square'; side: number }
function assertNever(value: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(value)}`)
}
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.round(Math.PI * shape.r ** 2)
case 'square':
return shape.side ** 2
default:
return assertNever(shape)
}
}
console.log(area({ kind: 'circle', r: 2 }))
console.log(area({ kind: 'square', side: 3 }))Result
13 9
Definition and usage
#The never type describes a situation that can’t happen. A function that returns never never ends with an ordinary return: it always throws an exception or runs in an infinite loop.
Its most practical use is checking exhaustiveness. If you handle every variant of a union in a switch, the value has the type never in the default branch. When someone adds a new variant and forgets to handle it, the compiler reports an error.
never also shows up on its own as the result of narrowing, once you’ve ruled out every possible type, and in conditional types as a way to “remove” a member of a union.
Syntax
#Syntax
function fail(message: string): never {
throw new Error(message)
}Good practices
#- An
assertNeverfunction in thedefaultbranch is a simple way to make the compiler remind you about new variants. - Don’t use
neveras an “empty type” for variables. Nothing can be assigned to it.
Related entries
#- void vs nevervoid means a function returns no useful value, while never means a function never returns at all: it throws an error or runs forever.
- Discriminated unionsUnions of objects with a shared tag field that makes it easy to tell the variants apart.
- voidThe return type of functions that return nothing.
- Type narrowingDetermining a more precise type for a value based on checks in your code.
- Conditional typesTypes chosen based on a condition: T extends U ? X : Y.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.