类型操作
约 608 字大约 2 分钟
2026-02-09
联合类型与交叉类型
联合类型
联合类型使用 | 表示,表示值可能是多个类型之一
// id 可以是 string 或 number
function formatId(id: string | number) {
if (typeof id === 'string')
return id.toUpperCase()
return id.toString()
}交叉类型
交叉类型使用 & 表示,表示值同时具备多个类型
person.d.ts
interface PersonBase {
name: string
}
interface Worker {
company: string
}person.ts
// Employee 既要满足 PersonBase,也要满足 Worker
type Employee = PersonBase & Worker
const employee: Employee = {
name: 'zjs',
company: 'acme',
}字面量类型
有时我们不希望一个值只是 "字符串",而是希望它只能取某几个固定值
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
function request(method: HttpMethod) {
return method
}
request('GET')
request('PATCH') // 报错相关信息
字面量类型本质上是更精确的类型约束,实际开发中经常和联合类型一起使用
类型收窄
当一个值是联合类型时,TypeScript 往往需要先判断,再安全地使用更具体的能力。这个过程叫 类型收窄
function print(value: string | Date) {
// 走到后面的分支时,value 被缩小为 string
if (value instanceof Date) {
console.log(value.toISOString())
return
}
// value 被缩小为 string
console.log(value.toUpperCase())
}常见缩小方式:
typeof、instanceofin- 字面量相等判断(
===、!==) - 自定义类型守卫(
arg is Xxx)
in 守卫
interface Fish {
swim: () => void
}
interface Bird {
fly: () => void
}
function move(animal: Fish | Bird) {
if ('swim' in animal) {
animal.swim()
return
}
animal.fly()
}自定义类型守卫
interface Fish {
swim: () => void
}
interface Bird {
fly: () => void
}
// 返回值中的 animal is Fish 表示:
// 如果函数返回 true,TypeScript 就把 animal 视为 Fish
function isFish(animal: Fish | Bird): animal is Fish {
return 'swim' in animal // 通过判断是否存在 swim 属性来收窄类型
}类型断言
类型断言用于告诉编译器“我比你更清楚这个值的类型”
const el = document.getElementById('avatar') as HTMLImageElement
el.src = '/avatar.png'警告
断言不会做运行时校验,错误断言会把问题推迟到运行时
非空断言 !
当你明确知道值不为 null 或 undefined 时,可以使用非空断言
function printUpper(input?: string) {
console.log(input!.toUpperCase())
}更推荐先做显式判断:
function printUpperSafe(input?: string) {
if (!input) return
console.log(input.toUpperCase())
}as const 与 satisfies
as const
用于把对象或数组推导成只读字面量
const config = {
method: 'GET',
retry: 3,
} as constsatisfies
用于“校验结构,但不丢失推导精度”
interface RequestConfig {
method: 'GET' | 'POST'
retry: number
}
const config = {
method: 'GET',
retry: 3,
} satisfies RequestConfig
// config.method 仍然是字面量 'GET'