单元类型

单元类型(Unit Type)也叫作单例类型(Singleton Type),指的是仅包含一个可能值的类型。由于这个特殊的性质,编译器在处理单元类型时甚至不需要关注单元类型表示的具体值。

TypeScript 中的单元类型有以下几种:

  • undefined 类型。

  • null 类型。

  • unique symbol 类型。

  • void 类型。

  • 字面量类型。

  • 联合枚举成员类型。

我们能够看到这些单元类型均只包含一个可能值。示例如下:

const a: undefined = undefined;
const b: null = null;
const c: unique symbol = Symbol();
const d: void = undefined;
const e: 'hello' = 'hello';

enum Foo { A, B }
const f: Foo.A = Foo.A;