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

如何定义包含可变键同类型值的Steam白名单TypeScript对象类型

TypeScript定义Steam白名单对象类型

要实现键为字符串类型(Steam游戏ID)、值为steamRec类型的精确对象类型,无需使用宽泛的object类型,有两种实用方案:

方案1:手动定义索引签名

通过索引签名明确约束对象的键和值类型:

type steamWhitelistObject = {
  [gameId: string]: steamRec;
};

其中[gameId: string]指定所有键为字符串(对应Steam游戏ID),每个键对应的值必须是你已定义好的steamRec类型。

方案2:使用TypeScript内置Record工具类型

利用官方提供的Record工具类型,写法更简洁直观:

type steamWhitelistObject = Record<string, steamRec>;

Record<K, T>是TypeScript专门用于定义键类型为K、值类型为T的对象类型,完全匹配你的需求。

示例验证

假设你已定义的基础类型如下:

type steamRecKey = 'appId' | 'name';
type steamRecValue = string | number;
type steamRec = {
  [key in steamRecKey]: steamRecValue;
};

使用上述方式定义白名单类型后,即可创建符合规范的白名单对象:

const mySteamWhitelist: steamWhitelistObject = {
  '440': { appId: '440', name: 'Team Fortress 2' },
  '730': { appId: '730', name: 'Counter-Strike 2' }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:16:07