Partial

Partial的作用是将类型T中的所有属性变为可选属性

type Partial<T> = {
[P in keyof T]?: T[P];
};
interface IAnimal {
name: string
age: number
color: string
}
type MyPartial = Partial<IAnimal>
// 转换结果:
type MyPartial = {
name?: string;
age?: number;
color?: string;
}

Required

Required作用是将所有属性变成必选属性

type Required<T> = {
[P in keyof T]-?: T[P];
};

Readonly

Readonly作用是将所有属性变成只读属性

type Readonly<T> = {
readonly [P in keyof T]: T[P];
};

Pick<T, K>

Pick的作用是在对象中选取一部分属性

type MyPick = Pick<IAnimal, "name" | "age">

Exclude<T, U>

Exclude<T, U>表示从T中排除U类型或类型集合

type MyExclude = Exclude<string | number | boolean, string>

此外,我们可以将Exclude融入对象类型,针对属性值进行排除,如

type ExcludeAnimal = {
[key in Exclude<keyof IAnimal, string>]: IAnimal[key]
}

上述代码实现的是将IAnimal中字符类型属性名全部排除,也就是将属性全清除

Omit<T, K>

Omit<T, K>的含义是从T对象类型中删除K,比如我们可以删除IAnimal的age和color

type OmitAnimal = Omit<IAnimal, "age" | "color">

Record<K, T>

Record可以理解为批量创建一个对象中的属性,其中键值或其集合是K,类型是T。我们使用Record表示一下上面的IAnimal

type RecordAnimal = Record<"name" | "color", string> & Record<"age", number>

NonNullable

NonNullable一般用来从类型T中排除空类型,即判断是否存在null或undefined,如果不是则返回原类型

NonNullable<null | undefined | string | boolean | number> // 表示 string | number | boolean

ReturnType

ReturnType是用来获取函数的返回值类型,其中T表示函数类型