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

TypeScript索引签名模板限制:如何限定Person属性数量?

解决TypeScript模板字符串索引签名TS(1337)错误的可行方案

你遇到的TS(1337)错误,本质是TypeScript不支持直接在索引签名里用person${AllowedIndex}Name这种模板字符串语法——索引签名只能用string、number、symbol这类基础类型,或者预定义的字面量联合,不能动态拼接。

但可以用映射类型实现你的需求,不用重复写每个键名,还能限定最多5个Person相关属性,步骤如下:

  1. 先定义允许的索引联合类型:
type AllowedIndex = 1 | 2 | 3 | 4 | 5;
  1. 用映射类型生成所有Person字段:
type PersonNameFields = {
  [K in AllowedIndex as `person${K}Name`]: string;
};

这里的as子句是映射类型的重映射特性,会遍历AllowedIndex的每个成员,把它转换成对应的模板字符串键(比如把1转成person1Name)。

  1. 把生成的字段合并到你的业务接口中:
interface Foo extends PersonNameFields {
  // 其他非Person相关字段
  id: number;
  department: string;
}

这样Foo接口就自动包含了person1Name到person5Name这5个字符串类型字段,完全不用手动重复编写,也不会触发TS(1337)错误。

如果需要扩展其他类似字段(比如person${K}Age),只需要再定义一个映射类型即可:

type PersonAgeFields = {
  [K in AllowedIndex as `person${K}Age`]: number;
};

interface Bar extends PersonNameFields, PersonAgeFields {
  // 其他字段
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:50:01