table of Contents
Definition of never
never
Other types (including null
and undefined
) sub-type, from the representative value does not occur.
There are usually two manifestations of never:
- Throw an exception
// 返回值为 never 的函数可以是抛出异常的情况 function error(message: string): never { throw new Error(message); }
- Cannot execute to the end point
// 返回值为 never 的函数可以是无法被执行到的终止点的情况 function loop(): never { while (true) { } }
Features of never
never
Variables of type can be assigned to variables of any type;let num: number; num = (() => { throw new Error('exception'); })();
never
Types of variables can only benever
the type of assignment variables.let invalid1: never; let invalid2: never; invalid1 = "Hello World!"; // error, string 类型不能转为 never 类型 invalid2 = (() => { throw new Error('exception'); })();