interface Info {
name : string,
age : number,
}
type optionalInfo = Partial<Info>
得到的新类型为:
type optionalInfo = {
name?: string | undefined;
age?: number | undefined;
}
实现Partial:使用映射进行属性遍历
type newPartial<T> = {
[key in keyof T]?: T[key]
}
interface Info {
name? : string,
age? : number,
}
type optionalInfo = Required<Info>
得到新的类型:
type optionalInfo = {
name: string;
age: number;
}
自己实现 Required,也是使用映射进行属性遍历
type newRequired<T> = {
[key in keyof T]-?: T[key]
}
interface Info {
name? : string,
age? : number,
}
type optionalInfo = Readonly<Info>
得到新的类型:
type optionalInfo = {
readonly name?: string | undefined;
readonly age?: number | undefined;
}
自己实现 Readonly:
type newReadonly<T> = {
readonly [key in keyof T]: T[key]
}
interface Info {
name? : string,
age? : number,
}
type k = "a" | "b" | "c"
type optionalInfo = Record<k, Info>
得到的新类型为:
type optionalInfo = {
a: Info;
b: Info;
c: Info;
}
自己实现 Record
type newRecord<K extends keyof Info, V> = {
[key in K]: V
}
interface Info {
name? : string,
age? : number,
}
type optionalInfo = Pick<Info, "name">
得到新的类型为
type optionalInfo = {
name?: string | undefined;
}
自己实现 Pick
type newPick<T, K extends keyof T> = {
[p in K]: T[p]
}
interface Info {
name? : string,
age? : number,
}
type optionalInfo = Omit<Info, "name">
得到的新类型为:
type optionalInfo = {
age?: number | undefined;
}
自己实现 Omit
type newOmit<T, K extends keyof T> = {
[p in keyof T as p extends K ? never : p]: T[p]
}
type k = "a" | "b" | "c"
type optionalInfo = Exclude<k, "a">
得到的新类型为:
type optionalInfo = "b" | "c"
自己实现 Exclude
type newExclude<T, E> = T extends E ? never : T
type k = "a" | "b" | "c"
type optionalInfo = Extract<k, "a">
得到的新类型为:
type optionalInfo = "a"
自己实现 Extract:
type newExtract<T, E> = T extends E ? T : never
type k = "a" | "b" | "c" | null | undefined
type optionalInfo = NonNullable<k>
得到的新类型为:
type optionalInfo = "a" | "b" | "c"
自己实现 NoneNullable:
type newNoneNullable<T> = T extends null | undefined ? never : T
下面会取到函数的返回值类型:
function fn():string{
return 'a'
}
type callbackType = ReturnType<typeof fn>
得到的新类型为:
type callbackType = string
自己实现 ReturnType:
type newReturnType<T extends (...args:any[])=>any> = T extends (...args:any[])=> infer R ? R : never
class Animal {}
function factory<T extends new (...args: any[]) => any>(constructor:T):InstanceType<T>{
return new constructor()
}
const d1 = factory(Animal)
这样就能保证d1
类型的正确
const d1: Animal
自己实现 InstanceType:
type newInstanceType<T extends new (...args:any[])=>any> = T extends new (...args:any[])=> infer R ? R : never