简体   繁体   中英

Infer arguments for abstract class in typescript

I'm trying to get the arguments for typescript classes and functions.

export type CtorArgs<TBase> = TBase extends new (...args: infer TArgs) => infer Impl ? TArgs : never;
export type AbsCtorArgs<TBase> = TBase extends {constructor: (...args: infer TArgs) => infer Impl} ? TArgs : never;
export type FuncArgs<TBase> = TBase extends (...args: infer TArgs) => infer Impl ? TArgs : never;

function RegularFunction(a:string,b:number){}
class RegularClass{
    constructor(a:string,b:number){}
}    
abstract class AbstractClass{
    constructor(a:string,b:number){}
}


type thing = [
    CtorArgs<typeof RegularClass>,
    FuncArgs<typeof RegularFunction>,
    AbsCtorArgs<typeof AbstractClass>,
    CtorArgs<typeof AbstractClass>,
    FuncArgs<typeof AbstractClass>
];

But for some reason abstract classes don't return arguments of their constructors. 只返回从不 I suspect this is because the new keyword isn't available on abstract classes . Does anybody know how to get those arguments which do actually exist for an abstract class constructor?

And no, this isn't about instantiating a abstract classes, this is about dependency injection to a class that inherits from an abstract class and the arguments to that class. See here

It is possible to infer parameters of abstract class. You just need to add abstract keyword before new .

See example:


abstract class AbstractClass {
    constructor(a: string, b: number) { }
}
export type InferAbstract<T> = T extends abstract new (...args: infer Args) => infer _ ? Args : never;

type Result = InferAbstract<typeof AbstractClass> // [a: string, b: number]

But you don't even need to use some custom utility types. You can use built it [ConstructorParameters][1] which was introduced in TS 3.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM