字面量类型把类型收窄到具体的值,比如 type Status = 'open' | 'closed'。它通常与联合类型搭配,形成一组可枚举的取值,替代简单的字符串校验:函数参数声明为字面量联合后,传入别的字符串会在编译期直接报错,配合编辑器还能自动补全所有合法取值。
配合 as const 可以把整个对象或数组固化为全字面量:const actions = ['start', 'stop'] as const 得到的是只读元组,元素类型是 start 或 stop。它比 enum 更轻量——enum 会生成运行时代码,字面量联合完全在编译期存在,是定义常量集合的首选方案。
type Status = 'open' | 'closed' | 'done'; function close(task: Status) { if (task === 'open') console.log('关闭任务'); } close('open'); // OK // close('paused'); // 报错:类型不匹配 const actions = ['start', 'stop'] as const; // actions 的类型是 readonly ['start', 'stop']