Typescript -字面量类型
在 TypeScript 中,字面量类型(Literal Types) 是一种将具体的值作为类型的机制,用于限制变量或参数只能接受特定的字面量值。它通过精确约束取值范围,增强代码的类型安全性
- 基础定义与类型
字面量类型分为三种: - 字符串字面量类型:如 “success”、“error”
- 数字字面量类型:如 0、1、42
- 布尔字面量类型:true 或 false(实际使用较少)
// 字符串字面量类型
type Status = "success" | "error";
let status: Status = "success"; // 只能赋值 "success" 或 "error"// 数字字面量类型
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
const roll: DiceRoll = 3; // 只能赋值 1-6// 布尔字面量类型(通常直接使用 boolean)
type IsReady = true;
let ready: IsReady = true; // 只能为 true
- 字面量类型的联合类型
字面量类型可以与其他字面量类型或原始类型联合使用,形成更灵活的类型定义。
type Color = 'red' | 'green' | 'blue';
type Size = 'small' | 'medium' | 'large';type ProductFilter = Color | Size;function applyFilter(filter: ProductFilter) {console.log(`Applying filter: ${filter}`);
}applyFilter('red'); // 正确
applyFilter('small'); // 正确
applyFilter('extra-large'); // 错误:Argument of type '"extra-large"' is not assignable to parameter of type 'ProductFilter'.
- 字面量类型与对象字面量
在对象字面量中使用字面量类型,可以确保对象的属性只能是特定的值。
type Role = 'admin' | 'user' | 'guest';interface User {name: string;role: Role;
}const user: User = {name: 'John Doe',role: 'admin' // 正确
};const user2: User = {name: 'Jane Doe',role: 'moderator' // 错误:Type '"moderator"' is not assignable to type 'Role'.
};
- 字面量类型与函数参数
在函数参数中使用字面量类型,可以限制函数调用时传入的参数值。
type LogLevel = 'info' | 'warning' | 'error';function log(message: string, level: LogLevel = 'info') {console.log(`[${level.toUpperCase()}] ${message}`);
}log('Application started'); // [INFO] Application started
log('File not found', 'warning'); // [WARNING] File not found
log('Critical error', 'critical'); // 错误:Argument of type '"critical"' is not assignable to parameter of type 'LogLevel'.
- 字面量类型与类型守卫
字面量类型可以与类型守卫结合使用,以便在函数内部进行更精确的类型检查。
type FileType = 'image' | 'video' | 'audio';function processFile(file: { type: FileType; data: any }) {if (file.type === 'image') {console.log('Processing image:', file.data);} else if (file.type === 'video') {console.log('Processing video:', file.data);} else if (file.type === 'audio') {console.log('Processing audio:', file.data);}
}processFile({ type: 'image', data: 'image.jpg' }); // 正确
processFile({ type: 'document', data: 'document.pdf' }); // 错误:Argument of type '"document"' is not assignable to parameter of type 'FileType'.
- 字面量类型与映射类型
字面量类型可以用于映射类型中,以创建灵活的类型转换。
type Key = 'name' | 'age' | 'email';type PartialUser<T> = {[K in Key]?: T;
};const user: PartialUser<string> = {name: 'John Doe',age: '30', // 错误:Type 'string' is not assignable to type 'number'.email: 'john@example.com'
};
- 字面量类型与模板字面量类型
字面量类型可以和其他字符串结合,形成模板字面量类型,用于生成新的类型。
type EventNames = 'click' | 'hover' | 'submit';
type EventCallback = (event: Event) => void;type EventListenerMap = {[K in EventNames]: EventCallback;
};const listeners: EventListenerMap = {click: (event) => console.log('Click event', event),hover: (event) => console.log('Hover event', event),submit: (event) => console.log('Submit event', event)
};
- 字面量类型与 as const 断言
as const 断言可以与字面量类型结合使用,确保变量的值不会被修改,并且类型被精确推断。
const directions = ['North', 'South', 'East', 'West'] as const;
type Direction = typeof directions[number]; // "North" | "South" | "East" | "West"function move(direction: Direction) {console.log(`Moving ${direction}`);
}move('North'); // 正确
move('Northeast'); // 错误:Argument of type '"Northeast"' is not assignable to parameter of type 'Direction'.