主题
字面量类型
字面量类型表示一个确定的值,而不是一类值。
例如 string 表示任意字符串,'hello' 只表示字符串字面量 hello。
基本示例
ts
let direction: 'up' | 'down'
direction = 'up'
direction = 'down'
// direction = 'left' // 报错和联合类型配合使用
字面量类型最常见的用法,是和联合类型一起表示“有限个可选值”。
ts
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
function request(url: string, method: RequestMethod) {
console.log(url, method)
}
request('/api/user', 'GET')const 和 let 的推断差异
ts
const status1 = 'success' // 类型是 'success'
let status2 = 'success' // 类型是 stringconst 更容易保留字面量类型,let 通常会被推断为更宽的基础类型。
