1.Pick<Type, Keys>
通过泛型选择指定的属性生成新的类型,获取新的类型。 2.1版本后引入。
官方文档写到:
Constructs a type by picking the set of properties `Keys`
(string literal or union of string literals) from `Type`
//通过设置keys获取新的对象的类型 创造新对象
interface List{
id: number
name: string
age: number
}
type NameId = Pick<List, 'name' | 'id'>
const nameId: NameId = {
name: "xiao",
id: 1,
}
//指定属性构造出了新类型
自己实现
type MappedType<T, Keys> = {
[Key in Keys]: T[Key];
};
2.Partial
通过泛型让目标类型中的所有属性变为可选属性生成一个新的类型, 2.1版本后引入
type ListOrNull = Partial<List>
const list: ListOrNull = {
}
//对象可以为空或者值为空、null...
3.Omit<Type, Keys>
通过泛型删除指定属性生成新的类型,3.5版本之后
type Age = Omit<List, 'name' | 'id'>
const age: Age = {
age: 1
}
链接: mp.weixin.qq.com/s?__biz=MzU… www.jianshu.com/p/90c08cfe4…