The never type in TypeScript

As neverthe Chinese definition of , a type in TypeScript represents a nevertype whose value never occurs. E.g:

type A = 'A';
type B = 'B';
type C = A & B;
复制代码

A union type Cis theA intersection of type and type , which means that its type value equals both and . This type of type definition is called a union type, which is supported in TypeScript, but the writing of this example means that the equal to and at the same time , which is obviously an impossible condition, so here type is type.BABCABCnever

Type information can be regarded as a set of elements, type Ais equivalent to set {'A'}, type Bis equivalent to a set {'B'}, type Cis equivalent to a set ,{} and type corresponds to an empty set.never

neverType can be used to declare the return type of a function, indicating that the function will not have any return value.

function a(): never {
  throw new Error('error');
}
复制代码

当然,void 类型也可以用于声明函数的返回值类型来表示函数没有任何返回值,但是 void 所表示的意思就不那么明确了。使用 void 的话,函数是可以返回 undefined 的,而采用 never 则不允许函数返回 undefined

function a(): void {
  return undefined; // 一切正常
}

function b(): never {
  return undefined; // 类型 'undefined' 不能分配给类型 'never'
}
复制代码

使用函数表达式创建的无返回值的函数在不指定函数返回值类型时,TypeScript 将自动推断其返回值类型为 never 类型。

但是,上述情况中如果采用函数声明创建函数,其返回值类型将会被推断为 void 类型。

这并非是 TypeScript 的 bug,之所以设计成这样是出于对向后兼容的考虑。现存的很多库中有大量抽象函数定义的返回值类型信息并没有明确指定为 void。由于这些函数是抽象的(抽象函数仅有类型信息,无函数功能实现),函数的具体实现交给了库使用者,使用者在实现过程中可自由决定函数是否有返回值。如果这种情况下函数类型被 TypeScript 推断为 never,则表示函数实现不能有返回值(函数实现中不可出现 return 关键字),很显然这样就出现了冲突,导致函数的实现无法被正确重写。

class AbstractClass {
    methodToBeOverriden() { // TypeScript 推断其返回类型为 void
        throw new Error('Not implemented!');
    }
}
复制代码

因此,在实际项目开发中,不能完全依赖于 TypeScript 的类型推断系统来帮助我们生成正确的类型信息。当需要明确表明函数无返回值时,需要将其返回值类型指定为 never

如果发现译文存在错误或其他需要改进的地方,欢迎到 掘金翻译计划 对译文进行修改并 PR,也可获得相应奖励积分。文章开头的 本文永久链接 即为本文在 GitHub 上的 MarkDown 链接。


The Nuggets Translation Project is a community that translates high-quality Internet technical articles. The source of the articles is the English sharing articles on Nuggets. The content covers Android , iOS , front-end , back- end , blockchain , products , design , artificial intelligence and other fields. If you want to see more high-quality translations, please continue to pay attention to the Nuggets translation plan , official Weibo , and Zhihu column .

Guess you like

Origin juejin.im/post/7079083161262653470