typescript - 根据超类构造函数参数定义类型
问题描述
我正在尝试基于超类的构造函数参数定义一个类型。
有没有一种方法可以在不定义自己的构造函数的情况下提取它,因为它并不是真正需要的?
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)
解决方案
原来我错过了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>
推荐阅读
- python - 将 Python 脚本与 scipy 和 numpy 库以及 Unity 一起使用的任何可行方法?
- javascript - 赛普拉斯等待所有 ajax 请求
- xamarin - Xamarin.forms 根据日期检索 Firebase 数据
- python - 在 Python 列表中按字典 ID 查找元素[字典]
- java - 如何将 txt 文件中的单词或数字声明为字符串
- spring - 用于安排 CRON 作业在周二至周六早上 6 点运行的 spring CRON 表达式?
- mongodb - 将 spring-boot-starter-data-mongodb 更新到更新版本
- android - Android:MotionLayout 无法将视图可见性设置为消失,视图保持可见
- ggplot2 - 图例未显示带有 2 个 x 轴的 ggplot2
- java - 无法连接到基于 Docker 的 Cassandra 容器 - “所有主机尝试查询失败”