You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中定义ConstructorParamsAsObject泛型类型?

问题描述

我想在TypeScript中动态生成类构造函数所有参数的对象类型。我了解ConstructorParameters工具类型,但它返回的是数组类型。我希望能像下面这样使用:

class Foo {
    constructor(public bar: string, public baz: number) {
    }
}

type ConstructorParamsAsObject<T>  = ???

const params: ConstructorParamsAsObject<typeof Foo> = {bar: "Foobar", baz: 30};
const foo = new Foo(params.bar, params.baz);

请问该如何定义这个泛型类型ConstructorParamsAsObject?

我已经尝试了以下方法,但未得到预期结果:

type FooConstructorParams = ConstructorParameters<typeof Foo>;
type ConstructorParamsAsObject = {
    [K in keyof FooConstructorParams]: FooConstructorParams[K]
}

const foo: ConstructorParamsAsObject = {
    0: "Foobar",
    1: 30
};
解决方案

针对构造函数参数为public的场景

你示例中的构造函数参数都用public修饰,这类参数会自动成为类的实例属性。利用这一点,我们可以通过InstanceType<T>获取类的实例类型,直接将其作为参数对象的类型:

type ConstructorParamsAsObject<T extends new (...args: any[]) => any> = InstanceType<T>;

测试代码:

class Foo {
    constructor(public bar: string, public baz: number) {
    }
}

type ConstructorParamsAsObject<T extends new (...args: any[]) => any> = InstanceType<T>;

const params: ConstructorParamsAsObject<typeof Foo> = {bar: "Foobar", baz: 30}; // 类型校验通过
const foo = new Foo(params.bar, params.baz); // 正常实例化

关于你之前尝试的问题

你之前的写法是遍历ConstructorParameters返回的元组索引,得到的是数字键(0、1)的对象,而非以参数名称为键的结构,这和预期不符。

通用场景说明

如果构造函数包含非public参数(如private/protected),TypeScript本身没有直接提取参数名称的内置能力——因为ConstructorParameters返回的元组仅保留类型信息,参数名称在类型层面会被擦除。这种情况下只能生成数字索引的对象,无法实现参数名称作为键的结构。

内容的提问来源于stack exchange,提问作者aTastyT0ast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 11:47:35