Never is primitive type, which represent value that will never occur. Never type introduced in TypeScript 2.0
You can use the when your function never returns any value or function contain unreachable code block.
// due to infinite while loop this function will never returns, its type is never function infiniteWhileLoop(): never { while (true) { console.log('Hello TypeScript'); } } function throwErrorMessage(message :string): never { throw new Error(message) }
function neverWithDataType(value: number|string) { if (typeof value === "string") { // Type string console.log(value); } else if (typeof value === "number") { // Type number console.log(value); } else { // Type never console.log(value); } }
never
and void
You might ask yourself why TypeScript needs a never
type when it already has a void
type. Although the two might seem similar, they represent two different concepts:
undefined
in JavaScript. Although we typically say that such a function "doesn't return anything", it returns. We usually ignore the return value in these cases. Such a function is inferred to have a void
return type in TypeScript.never
return type never returns. It doesn't return undefined
, either. The function doesn't have a normal completion, which means it throws an error or never finishes running at all.If you're interested in type theory, the never
type is a bottom type, also known as a zero type or an empty type. It's often denoted as ⊥ and signals that a computation doesn't return a result to its caller. The void
type, on the other hand, is a unit type (a type that allows only one value) with no defined operations.