1.利用keyof将某个interface里的索引全部变为只读,不允许修改(或者全部变为可选/必有)
interface Person {
name?: string
age: number
gender: number
}
type ReadOnlyType<T> = {
readonly [P in keyof T]: T[P]
}
type ReadOnlyType<T> = {
[P in keyof T]?: T[P]
}
type ReadOnlyType<T> = {
[P in keyof T]-?: T[P]
}
type ReadOnlyPerson = ReadOnlyType<Person>
2.利用keyof将某个interface里的索引全部转为联合类型
interface Person {
name: string
age: number
gender: number
}
type ReadOnlyType = keyof Person
3.利用&将两个interface组成一个新的interface,这个新的interface里面必须包含前两个interface的所有索引,缺一不可 ( | 二选一,用得多就不列举了)
interface Person {
name: string
}
interface Son {
age: string
}
type NewInterface = Person & Son
4.利用pick从一个interface中选择索引生成新的interface
type Pick<T, K extends keyof T> = { [P in K]: T[P]; }
interface Person {
name: string
age: string
c: string
}
type NewInterface = Pick<Person, 'name' | 'age'>
5.利用Omit从一个interface中排除部分择索引生成新的interface
type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }
interface Person {
name: string
age: string
c: string
}
type NewInterface = Omit<Person, 'name' | 'age'>
6. 利用InstanceType从一个类里面获取interface
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any
class A {
name: string
age: string
c: string
constructor(name: string, age: string, c: string) {
this.name = name
this.age = age
this.c = c
}
}
type NewInterface = InstanceType<typeof A>
|