字面量类型

TypeScript 支持将字面量作为类型使用,我们称之为字面量类型。每一个字面量类型都只有一个可能的值,即字面量本身。

boolean 字面量类型

boolean 字面量类型只有以下两种:

  • true 字面量类型。

  • false 字面量类型。

原始类型 boolean 等同于由 true 字面量类型和 false 字面量类型构成的联合类型,即:

type BooleanAlias = true | false;

true 字面量类型只能接受 true 值;同理,false 字面量类型只能接受 false 值,示例如下:

const a: true = true;

const b: false = false;

boolean 字面量类型是 boolean 类型的子类型,因此可以将 boolean 字面量类型赋值给 boolean 类型,示例如下:

const a: true = true;
const b: false = false;

let c: boolean;
c = a;
c = b;

string 字面量类型

字符串字面量和模板字面量都能够创建字符串。字符串字面量和不带参数的模板字面量可以作为 string 字面量类型使用。示例如下:

const a: 'hello' = 'hello';

const b: `world` = `world`;

string 字面量类型是 string 类型的子类型,因此可以将 string 字面量类型赋值给 string 类型。示例如下:

const a: 'hello' = 'hello';
const b: `world` = `world`;

let c: string;
c = a;
c = b;

数字字面量类型

数字字面量类型包含以下两类:

  • number 字面量类型。

  • bigint 字面量类型。

所有的二进制、八进制、十进制和十六进制数字字面量都可以作为数字字面量类型。示例如下:

const a0: 0b1 = 1;
const b0: 0o1 = 1;
const c0: 1 = 1;
const d0: 0x1 = 1;

const a1: 0b1n = 1n;
const b1: 0o1n = 1n;
const c1: 1n = 1n;
const d1: 0x1n = 1n;

除了正数数值外,负数也可以作为数字字面量类型。示例如下:

const a0: -10 = -10;
const b0: 10 = 10;

const a1: -10n = -10n;
const b1: 10n = 10n;

number 字面量类型和 bigint 字面量类型分别是 number 类型和 bigint 类型的子类型,因此可以进行赋值操作。示例如下:

const one: 1 = 1;
const num: number = one;

const oneN: 1n = 1n;
const numN: bigint = oneN;

枚举成员字面量类型

在 5.4 节中介绍了联合枚举成员类型。我们也可以将其称作枚举成员字面量类型,因为联合枚举成员类型使用枚举成员字面量形式表示。示例如下:

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

const up: Direction.Up = Direction.Up;
const down: Direction.Down = Direction.Down;
const left: Direction.Left = Direction.Left;
const right: Direction.Right = Direction.Right;

关于枚举类型的详细介绍请参考5.4节。