指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

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 可以提供方向的自动完成。
单一数据源:数组和类型定义在一起,易于维护。
可扩展:添加新方向只需修改数组。