我正在尝试基于超类的构造函数参数定义类型。
是否有一种方法可以提取它而不定义自己的构造函数,因为它并不是真正需要的?
somelib/BaseClass.ts
export default abstract class BaseClass {
constructor(protected options: { key: string }) {}
}
src/AClass.ts
import BaseClass from 'somelib/BaseClass';
export default class AClass extends BaseClass {}
src/index.ts
import AClass from './AClass.ts'
type Constructor<T> = new (...args: any[]) => T;
type ConstructorFirstParameter<T extends Constructor<any>> = T extends new (
options: infer O,
...rest: any
) => any
? O
: never;
type Options = ConstructorFirstParameter<AClass>
我收到一个错误
Type 'AClass' does not satisfy the constraint 'Constructor<any>'.
Type 'AClass' provides no match for the signature 'new (...args: any[]): any'.ts(2344)
答案 0 :(得分:0)
原来我错过了typeof AClass
import AClass from './AClass.ts'
type Constructor<T> = new (...args: any[]) => T;
type ConstructorFirstParameter<T extends Constructor<any>> = T extends new (
options: infer O,
...rest: any
) => any
? O
: never;
type Options = ConstructorFirstParameter<typeof AClass>