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

TypeScript中能否定义映射类型等效的泛型类?

问题:

能否定义一个类,其属性名称无法预先确定(但属性类型均相同),且TypeScript能识别该类实例的所有属性?

如果只是定义类型,我会这样写:

type SavedNumbers<TName extends string[]> = { [key in TName[number]]: number }

const foo: SavedNumbers<['a', 'b']> = {
  a: 0,
  b: 0,
}

但我尚未找到定义等效类的方法。


已尝试的解决方案

我尝试了多种方法,其中包括:

  • 将类定义为实现映射类型,示例如下:
type SavedNumbers<TName extends string[]> = { [key in TName[number]]: number }

class Foo<
    TInstanceNames extends string[] = []
  > 
  implements SavedNumbers<TInstanceNames> {
  /* ... */
}

但显然implements仅适用于接口。

  • 使用extends尝试同样操作,遇到类似问题(仅支持继承类)。

  • 将映射类型纳入类声明:

class Foo<TCustomNames extends string[] = []> {
  [key in TCustomNames[number]]: number
  /* ... */
}

但这种方式也无效。


替代方案:将类型实例传入函数以添加类方法

例如,先定义:

function addMethods<T extends Record<string, number>>(x: T) {
  const plusOne = (a: number) => a + 1; 

  return Object.assign(x, {plusOne})
}

然后使用:

const foo = addMethods({a: 0, b: 0})
foo.a // 无错误;TypeScript识别'foo'上存在属性'a';
foo.b // 同理。
foo.c // 错误:"Property 'c' does not exist on type '{ a: number; b: number; } & { plusOne: (a: number) => number; }'."
    ~

但这种方法无法充分利用class提供的所有便利。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:34:58