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

如何获取TypeScript类构造函数参数的类型?

获取TypeScript类构造函数参数或实例属性的类型

在函数式场景下,我们可以轻松通过Parameters工具类型获取函数参数的类型:

function Test(props: {a: number}) {
  return props.a;
}

type A = Parameters<typeof Test>[0]["a"]; // 类型为number

但针对类组件(或普通类),直接访问constructor会触发类型报错——这是因为Test.constructor或Test["constructor"]指向的是通用的Function构造函数,而非当前类的构造函数类型,不符合Parameters的约束条件。

正确获取构造函数参数类型

直接使用typeof Test即可拿到类的构造函数类型,再配合Parameters工具类型:

class Test {
  a: number

  constructor(a: number) {
    this.a = a
  }
}

// 获取构造函数第一个参数的类型
type ConstructorParamA = Parameters<typeof Test>[0]; // 类型为number

额外:获取类实例的属性类型

如果需要获取类实例上属性的类型,可以使用InstanceType工具类型:

// 获取Test实例中a属性的类型
type InstancePropA = InstanceType<typeof Test>["a"]; // 类型为number

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:05:37