1.Partial
构造一个所有属性的都为可选的类型
type Partial<T> = {
[P in keyof T]?: T[P]
}
2.Pick<Type, Keys>
从一个类型中选取部分属性 构成一个新的类型
type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
interface Todo {
title: string
description: string
completed: boolean
}
type TodoPreview = Pick<Todo, "title" | "completed">
const todo: TodoPreview = {
title: "Clean room",
completed: false,
}
3.Exclude<Type, ExcludedUnion>
在联合类型中排除一个类型构建新类型
<!--如果T能赋值给U,返回never类型,最终会将T中属于U的属性移除-->
type Exclude<T, U> = T extends U ? never : T
type T1 = Exclude<"a" | "b" | "c", "a" | "b"> //type T1 = "c"
4.Extract
获取类型交集 和Exclude相反
<!--提取T中包含在U中的属性-->
type Extract<T, U> = T extends U ? T : never
type T0 = Extract<"a" | "b" | "c", "a" | "b"> //type T0 = "a" | "b"
5.Omit<Type, Keys>
通过用Exclude删除keys 然后用pick选取属性构造新类型 比exclude高级一点在于 用pick实现了在对象中选取 不局限于在联合类型中做排除
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>
interface Todo {
title: string
description: string
}
type TodoPreview = Omit<Todo, "description">
const todo: TodoPreview = {
title: "Clean room",
}
6.ReturnType
构造一个由 function 的返回类型组成的类型
type T0 = ReturnType<() => string>
7.Record
用于构建一个对象类型,将一种类型的属性映射到另一种类型
type Record<K extends keyof any, T> = {
[P in K]: T
}
interface CatInfo {
age: number
breed: string
}
type CatName = "miffy" | "boris"
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
}
8.keyof
keyof 类似于object.keys() 返回属性名组合成的联合类型
interface IProps {
title: string
content: string
}
type props = keyof IProps // 'title' | 'content'
9.typeof
用来获取一个变量或对象的类型
interface Person {
name: string;
age: number;
}
const sem: Person = { name: "semlinker", age: 30}
type Sem = typeof sem; // type Sem = Person