Skip to main content

Why should we use `never` in switch case in typescript

When to use

Handle all case in switch case statement.
Especially in enum type, custom union type.

Why to use

Especially enum type, we want to handle all cases in switch - case statement.
If we just write default is not enough. Maybe it doesn't handle other cases according to in enum, or custom type you defined.

How to use

Make variable never type from function argument.
Typescript compiler would check that are there missing types not handled above case: .

info

never type is used when you are sure that something is never going to occur.

Refer to official typescript never document

Example 1

interface Pig {
kind: 'pig',
growling(): void
}
interface Rooster {
kind: 'rooster'
growling(): void
}

interface Cow {
kind: 'cow'
growling(): void
}

interface Sheep {
kind: 'sheep',
growling(): void
}

type FarmAnimal = Pig | Rooster | Cow | Sheep

function printGrowling(animal: FarmAnimal) {
switch (animal.kind) {
case "pig":
animal.growling()
return
case 'rooster':
animal.growling()
return
case 'cow':
animal.growling()
return
// case 'sheep':
// animal.growling()
// return
default:
// `never` type is used when you are sure that something is never going to occur.
// To enforce handling all types , You should make variable `never` type.
// ⚠️ Typescript compiler notify you should handle `sheep` since not able to assign `sheep` type into `never`.
const _exhaustiveCheck: never = animal
throw new Error(_exhaustiveCheck)
}
}

Typescript compiler warn you in default clause, and make you implement all case.
Write your code safely in typescript using never type!.

🔗 Reference