Imagine having a set of conditions with different possible values and wanting to cover each potential case. In the event of adding a new condition in the future but forgetting to handle it, it is important to have an error detection mechanism—ideally catching errors before deployment rather than at run-time.
The question arises: How does one verify that a variable belongs to the type never
?
type Task = { type: 'update'; payload: any } | { type: 'delete'; payload: any }
const handleTask = (task: Task) => {
const update = (task: Task) => {
console.log(task)
}
const del = (task: Task) => {
console.log(task)
}
if (task.type === 'update') {
update(task)
} else if (task.type === 'delete') {
del(task)
} else {
// The variable 'task' is essentially of type 'never' here,
// This throws an error only if more types are added to the `Task.type` definition.
throw new Error(`Unhandled task.type "${(task as Task).type}".`)
}
}