The never type represents values that never occur. It is used for functions that either throw an error or run indefinitely, meaning they never complete or return a value.
Example 1: Function that Throws an Error
function error(message: string): never {
throw new Error(message); // The function doesn't return, it throws an error
}- A function that throws an error has the return type
never, because it never completes successfully or returns a value.
Example 2: Inferred Return Type of never
function fail() {
return error("Something failed"); // Inferred return type is `never`
}- The return type of
failis inferred asneverbecause it callserror, which never completes.
Example 3: Infinite Loop
function infiniteLoop(): never {
while (true) {} // Infinite loop, function never ends
}- A function with an infinite loop also has a
neverreturn type because it never finishes and never returns a value.
Key Points:
neveris used for functions that never return, either because they throw an error or run indefinitely.- A function with a
neverreturn type has an unreachable endpoint and will not complete its execution normally.