首页 > 解决方案 > 根据超类构造函数参数定义类型

问题描述

我正在尝试基于超类的构造函数参数定义一个类型。

有没有一种方法可以在不定义自己的构造函数的情况下提取它,因为它并不是真正需要的?

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)

标签: typescript

解决方案


原来我错过了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>

工作示例


推荐阅读