类型推断的妙用
TypeScript 的类型推断非常强大,很多时候不需要显式标注类型:
// 不需要显式标注
const name = 'Jay' // string
const age = 25 // number
const items = [1, 2, 3] // number[]
实用的工具类型
Partial 和 Required
interface User {
name: string
age: number
email: string
}
// 所有属性变为可选
type PartialUser = Partial<User>
// 所有属性变为必需
type RequiredUser = Required<PartialUser>
Pick 和 Omit
// 选取部分属性
type UserBasic = Pick<User, 'name' | 'age'>
// 排除部分属性
type UserWithoutEmail = Omit<User, 'email'>
Record
type StatusMap = Record<string, {
label: string
color: string
}>
const statuses: StatusMap = {
active: { label: '活跃', color: 'green' },
inactive: { label: '不活跃', color: 'gray' },
}
类型守卫
自定义类型守卫
interface Cat {
meow: () => void
}
interface Dog {
bark: () => void
}
function isCat(animal: Cat | Dog): animal is Cat {
return 'meow' in animal
}
function handleAnimal(animal: Cat | Dog) {
if (isCat(animal)) {
animal.meow() // TypeScript 知道这是 Cat
} else {
animal.bark() // TypeScript 知道这是 Dog
}
}
模板字面量类型
type EventName = 'click' | 'focus' | 'blur'
type EventHandler = `on${Capitalize<EventName>}`
// 'onClick' | 'onFocus' | 'onBlur'
条件类型
type IsString<T> = T extends string ? true : false
type A = IsString<string> // true
type B = IsString<number> // false
实际应用:API 响应类型
interface ApiResponse<T> {
code: number
message: string
data: T
}
interface UserData {
id: number
name: string
}
// 使用
async function fetchUser(id: number): Promise<ApiResponse<UserData>> {
const response = await fetch(`/api/users/${id}`)
return response.json()
}
总结
TypeScript 的类型系统比很多人想象的要强大得多。善用工具类型、类型守卫和条件类型,可以写出更安全、更可维护的代码。
评论💌 留下你的痕迹