掘金 后端 ( ) • 2024-06-26 17:58

  在 TypeScript 中,字符串字面量类型(String Literal Types)是一种特殊的类型,它表示一组特定的字符串值。使用字符串字面量类型,你可以限制变量或参数的取值范围,使代码更具可读性和安全性。

基本概念

字符串字面量类型允许你指定一个变量只能取某些特定的字符串值,而不是任意的字符串。

示例

type Direction = 'north' | 'south' | 'east' | 'west';

let direction: Direction;

direction = 'north'; // 正确
direction = 'south'; // 正确
direction = 'up';    // 错误,不能赋值 'up',因为它不是 'north' | 'south' | 'east' | 'west' 中的一个

在这个例子中,Direction 类型限定了变量 direction 只能是 'north'、'south'、'east' 或 'west'。

字符串字面量类型的用途

  1. 函数参数:限制函数参数的取值范围,提高代码的可读性和安全性。
type Color = 'red' | 'green' | 'blue';

function setColor(color: Color) {
  // 只能传递 'red'、'green' 或 'blue'
}

setColor('red');   // 正确
setColor('yellow'); // 错误,'yellow' 不是 Color 类型
  1. 对象属性:定义对象属性时,限制属性值的取值范围。
type Status = 'active' | 'inactive' | 'pending';

interface User {
  name: string;
  status: Status;
}

const user: User = {
  name: 'Alice',
  status: 'active', // 正确
};
  1. 枚举替代:在某些情况下,字符串字面量类型可以用来替代枚举类型(Enum),使代码更简洁。
// 使用字符串字面量类型
type Shape = 'circle' | 'square' | 'triangle';

function drawShape(shape: Shape) {
  // 绘制形状的逻辑
}

drawShape('circle');  // 正确
drawShape('hexagon'); // 错误

字符串字面量类型的结合

字符串字面量类型可以与联合类型和类型别名结合使用,定义更复杂的类型。

type Size = 'small' | 'medium' | 'large';
type Color = 'red' | 'green' | 'blue';

type TShirt = {
  size: Size;
  color: Color;
};

const myTShirt: TShirt = {
  size: 'medium',
  color: 'blue',
};

在这个例子中,TShirt 类型结合了 Size 和 Color 两个字符串字面量类型,定义了一个 T 恤的规格。

总结

  字符串字面量类型是 TypeScript 强类型系统的一部分,可以帮助你在编写代码时限定变量的取值范围,提高代码的可读性和安全性。通过定义具体的字符串值集合,可以避免无效的赋值操作,并使代码更加简洁明了。