ts字符串字面量联合类型的使用:
direction.ts:
export type Direction = "north" | "south" | "east" | "west"; // 在 TypeScript 中有一个专业术语来描述它:字符串字面量联合类型(String Literal Union Type)
export const directions: Direction[] = ["north","south","east","west"];
分析:
这里,"north"、"south"、"east" 和 "west" 都是字符串字面量类型。
与 const 断言的结合:
从 TypeScript 3.4 开始,你还可以使用 as const 来创建只读的字符串字面量联合类型:
const directions = ["north","south","east","west"] as const;
export type Direction = typeof directions[number];
这种方法的优点:
类型安全:只允许使用预定义的方向。
自动完成:IDE 可以提供方向的自动完成。
单一数据源:数组和类型定义在一起,易于维护。
可扩展:添加新方向只需修改数组。
