export { }
// ts 内置类型 源码分析笔记
type Parameters<T extends ( ...args: any ) => any> = T extends ( ( ...args: infer P ) => any ) ? P : never;
//type Parameters<T> = T extends ( ( ...args: infer P ) => any ) ? P : never; // 简写版
// type ReturnType<T> = T extends ( ( ...args: any ) => infer R ) ? R : never;
function add ( a: number, b: number ): number {
return a + b;
}
// 获取参数type
type ParametersType = Parameters<typeof add>
//获取返回值type
type ReturnType2 = ReturnType<typeof add>
type ConstructorParameters<T extends new ( ...args: any ) => any> = T extends new ( ...args: infer P ) => any ? P : never;
// type ConstructorParameters<T> = T extends new ( ...args: infer P ) => any ? P : never; // 简写版
class Person {
constructor ( name: string, age: number ) {
}
}
// 获取构造函数的参数类型
type paramsType = ConstructorParameters<typeof Person>
type InstanceType<T> = T extends new ( ...args: any ) => infer R ? R : any
const p = new Person( 'xiaocao', 10 )
type instanceType = InstanceType<typeof Person>
type OrTypes<T> = T extends Array<infer P> ? P : never
type Tuple = [ string, number ]
// t1 = string | nuber
type t1 = OrTypes<Tuple>
// 如果是实体则返回any,如果是函数,则返回函数类型,写的有问题,不知道该如果描述实例跟构造函数
// type OrTypes2<T> = T extends ( () => any ) ? any : T extends new ( ...args: any ) => infer R ? R : never
// type t2 = OrTypes2<typeof p>
// 联合推导
type T1 = { name: string }
type T2 = { age: number }
type ToInstance<T> = T extends { a: ( x: infer U ) => void, b: ( x: infer U ) => void } ? U : never
// T3 = T1 & T2
type T3 = ToInstance<{ a: ( x: T1 ) => void, b: ( x: T2 ) => void }>
// 变可选参数
type Partial<T> = {
[ P in keyof T ]+?: T[ P ]
}
// 深度对象可选项
type DepPartial<T> = {
[ U in keyof T ]+?: T[ U ] extends object ? DepPartial<T[ U ]> : T[ U ]
}
// Required<T> 必选项
type Required<T> = {
// -? 不可选 +?可选(可忽略)
[ P in keyof T ]-?: T[ P ]
}
// 可选项变成必选项
type DepRequired<T> = {
[ U in keyof T ]-?: T[ U ] extends object ? DepRequired<T[ U ]> : T[ U ]
}
//
type Readonly<T> = {
readonly [ P in keyof T ]?: T[ P ]
}
type SetDiff<A, B> = A extends B ? never : A
type getSame<A, B> = A extends B ? A : never
// type Extract<T, U> = T extends U ? T : never;
type ReadonlySome<T extends any, U extends any> = {
readonly [ P in getSame<keyof T, keyof U> ]: T[ P ]
}
type Pick<T, K extends keyof T> = {
[ P in K ]: T[ P ];
};
interface Dog {
name: string
kind: string
age: number
}
interface Animal {
name: string
kind1: boolean
}
// Pick 摘取某一些返回
type a1 = Extract<keyof Animal, keyof Dog>
type d1 = getSame<Animal, Dog>
type a = ReadonlySome<Animal, Dog>
// 过滤掉某些属性
type Omit<T, K extends keyof any> = {
[ P in SetDiff<keyof T, K> ]: T[ P ]
}
type oo1 = Omit2<Dog, 'age'>
type Omit2<T, K extends keyof any> = Pick<T, SetDiff<keyof T, K>>
type oo2 = Omit2<Dog, 'age'>
// type Omit3<T, K extends keyof any> = ( T, K ) => Pick<T, SetDiff<keyof T, K>>
|