TypeScript 内置类型
1. Partial转化可选属性
interface Company {
num: number
}
interface Person {
name: string,
age: string,
company: Company
}
type PartialPerson = Partial<Person>;
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K]
}
type DeepPartialPerson = DeepPartial<Person>;
2. Required转化必填属性
interface Company2 {
num: number
}
interface Person2 {
name: string,
age: string,
company: Company2
}
type PartialPerson2 = Partial<Person2>;
type RequiredPerson2 = Required<PartialPerson2>
3. Readonly 转化仅读属性
type Readonly<T> = { readonly [K in keyof T]: T[K] }
type RequiredPerson = Readonly<Person>
4. Pick 挑选所需的属性
type Pick<T, U extends keyof T> = { [P in U]: T[P] }
type PickPerson = Pick<Person, 'name' | 'age'>
5. Record记录类型
type Record<K extends keyof any, T> = { [P in K] : T }
let person: Record<string, any> = { name: 'xiaomi', age: 11 };
function map<T extends keyof any, K, U>(obj: Record<T, K>, callback: (item: K, key: T) => U) {
let result = {} as Record<T, U>
for (let key in obj) {
result[key] = callback(obj[key], key)
}
return result
}
const r = map({ name: 'zf', age: 11 }, (item, key) => {
return item
});
6. Omit忽略属性
let person2 = {
name: '123',
age: 11,
address: '456'
}
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type OmitAddress = Omit<typeof person2, 'address'>