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

TypeScript中如何为动态键的对象指定类型?

如何为动态键值对的对象定义TypeScript类型?

当然可以,对于这种键为字符串、值为数字的动态对象,你可以通过索引签名或者Record工具类型来定义Clients类型:

方法1:使用索引签名

直接明确对象的键类型与对应值类型:

type Clients = {
  [key: string]: number;
};

方法2:使用Record工具类型

Record是TypeScript内置工具类型,专门用于定义键值对结构,写法更简洁:

type Clients = Record<string, number>;

修正你代码中的类型问题

原代码存在几处类型错误,需要一并修正:

  1. document.querySelectorAll('.clients')返回的是NodeListOf<HTMLElement>,而非HTMLElement,类型需匹配;
  2. getAttribute返回值为string | null,需要将值转换为数字,同时处理可能的null情况;
  3. 赋值逻辑有误,应将data-client-value的数值赋给data-client-name对应的键,而非从clients中取值。

修正后的完整代码:

type Clients = Record<string, number>;

const clients: Clients = {};

// 修正元素集合的类型定义
const htmlElementCollection: NodeListOf<HTMLElement> = document.querySelectorAll('.clients');

htmlElementCollection.forEach(c => {
  const clientName = c.getAttribute('data-client-name');
  const clientValueStr = c.getAttribute('data-client-value');
  
  // 过滤无效值,避免类型错误与运行时异常
  if (clientName && clientValueStr) {
    const clientValue = parseFloat(clientValueStr);
    if (!isNaN(clientValue)) {
      clients[clientName] = clientValue;
    }
  }
});

这样定义后,TypeScript会正确约束clients对象的键为字符串、值为数字,同时规避了潜在的类型问题与运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:38:35