TypeScript 的类型系统是图灵完备的,这意味着你可以用类型来实现各种复杂的逻辑。本文将带你从入门到进阶。
type IsString<T> = T extends string ? true : false
type A = IsString<string> // true
type B = IsString<number> // false
type Readonly<T> = {
readonly [P in keyof T]: T[P]
}
type Optional<T> = {
[P in keyof T]?: T[P]
}
type EventName = `on${Capitalize<string>}`
// "onClick" | "onHover" | ...
type CSSProperty = `${string}-${string}`
// "margin-top" | "font-size" | ...
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object
? DeepReadonly<T[P]>
: T[P]
}
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object
? DeepPartial<T[P]>
: T[P]
}
interface User {
name: string
profile: {
age: number
address: {
city: string
}
}
}
type PartialUser = DeepPartial<User>
// 所有属性都变为可选,包括嵌套的
type PathKeys<T> = T extends object
? {
[K in keyof T & string]: K | `${K}.${PathKeys<T[K]>}`
}[keyof T & string]
: never
type UserPaths = PathKeys<User>
// "name" | "profile" | "profile.age" | "profile.address" | "profile.address.city"
推荐 Type Challenges,从 Easy 到 Hard 循序渐进。
TypeScript 的类型系统非常强大,掌握高级类型可以让你写出更安全、更优雅的代码。但也要注意适度,不要为了炫技而过度使用复杂类型。
正在加载评论...