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

如何在TypeScript中为对象实现的字典定义类型?

对象作为字典的类型定义问题

我常把对象用作字典,示例代码如下:

type Foo = { a: string }

type MyDictionary = { [key: string]: Foo }

function foo(dict: MyDictionary) {
  // 需求1:类型应为Foo[]
  const values = Object.values(dict)

  // 需求2:类型应为Foo | undefined
  const aValue = dict.b

  // 需求3:此处应报错
  dict.c = undefined
}

解决方案1

我通常会这么定义:

type MyDictionary = Record<string, Foo> // 等价于 { [key: string]: Foo }

该方案满足需求1和3,但不满足需求2。

解决方案2

{ [key: string]: Foo | undefined }

该方案满足需求2,但不满足需求1和3。

解决方案3

另一种选择是沿用方案1,同时使用更安全的获取函数:

export function safeGet<T extends {}, K extends keyof T>(obj: T, key: K): T[K] | undefined {
  return obj[key]
}

safeGet(dict, 'b')

是否有其他可行的解决方案?

注:我知道Map能很好地实现字典功能,但重构为Map并不总是可行的。本问题专门针对以对象实现的字典场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:05:10