// 获取函数参数的类型,组成一个元组类型的新类型typeParameters<TextendsFunction>=((...args:inferU)=>any)|(new(...args:inferU)=>any)?U:any[];declarefunctionf1(arg:{ a:number; b:string}):voidtypeT3= Parameters<typeof f1>// type T3 = [arg: {// a: number;// b: string;// }]typeT1= Parameters<(s:string, n:number)=>void>// type T1 = [s: string, n: nubmer]
ConstructorParameters<Type>
// 提取构造函数的参数类型,组成一个元组类型的新类型typeConstructorParameters<Textendsnew(...args:any)=>any>=Textendsnew(...args:inferP)=>any?P:neverclassC{constructor(a:number, b:string){}}typeT3= ConstructorParameters<typeofC>// type T3 = [a: number, b: string]
ReturnType<Type>
// 提取函数的返回值的参数类型,组成一个新类型typeReturnType<T>=Textends(...args:any[])=>inferR?R:anytypeT0= ReturnType<()=>string>// type T0 = stringdeclarefunctionf1():{ a:number; b:string}typeT4= ReturnType<typeof f1>// type T4 = {// a: number// b: string// }
InstanceType<Type>
// 提取实例对象的类型(对象实例化之前的class类)typeInstanceType<Textendsnew(...args:any)=>any>=Textendsnew(...args:any)=>inferR?R:anyclassC{
x =0
y =0}typeT0= InstanceType<typeofC>// type T0 = C
ThisParameterType<Type>
// 提取函数中 this 参数的类型,没有this 类型为 unknowntypeThisParameterType<T>=Textends(this:inferU,...args:any[])=>any?U:unknownfunctiontoHex(this: Number){returnthis.toString(16)}functionnumberToString(n: ThisParameterType<typeof toHex>){returntoHex.apply(n)}
OmitThisParameter<Type>
// 没有this参数,返回传入函数的类型// 有 this 参数,剔除this参数,并创建一个新的函数类型typeOmitThisParameter<T>=unknownextendsThisParameterType<T>?T:Textends(...args:inferA)=>inferR?(...args:A)=>R:TfunctiontoHex(this: Number){returnthis.toString(16)}functionnumberToString(n: ThisParameterType<typeof toHex>){returntoHex.apply(n)}
ThisType<Type>
// 充当对象执行上下文 this 的标记, 不返回类型。typeObjectDescriptor<D,M>={
data?:D
methods?:M& ThisType<D&M>// Type of 'this' in methods is D & M}functionmakeObject<D,M>(desc: ObjectDescriptor<D,M>):D&M{let data: object = desc.data ||{}let methods: object = desc.methods ||{}return{...data,...methods }asD&M}let obj =makeObject({
data:{ x:0, y:0},
methods:{moveBy(dx:number, dy:number){this.x += dx // Strongly typed thisthis.y += dy // Strongly typed this}}})
obj.x =10
obj.y =20
obj.moveBy(5,5)