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

TypeScript中泛型与直接类型重映射的行为差异

TypeScript元组直接重映射排除Array属性的解决方案

问题原因

TypeScript对泛型中的元组映射有特殊优化:当泛型参数T是元组时,{ [I in keyof T]: T[I] }会被识别为元组映射,自动忽略从Array继承的方法(如pop、toString)和非核心属性,只保留数字索引和length,最终输出元组类型。但直接对具体元组类型使用映射时,keyof 元组类型会包含所有继承自Array的属性键,导致映射结果变成包含大量额外属性的对象类型。

解决方案

方案1:键筛选排除非元组属性

使用映射类型的as子句,只保留元组的核心属性(数字索引字符串和length):

type Input = [string, number, boolean]

type Output2 = { 
  [I in keyof Input as I extends `${number}` | "length" ? I : never]: Input[I] 
}
// 输出:type Output2 = [string, number, boolean]

这里通过I extends ${number} | "length"筛选出元组的数字索引(字符串形式,如"0"、"1")和length属性,其余继承自Array的属性会被排除。

方案2:条件类型触发泛式元组处理

通过条件类型让TypeScript将具体元组类型当作泛型参数处理,触发元组映射优化:

type Input = [string, number, boolean]

type Output2 = Input extends readonly any[] 
  ? { [I in keyof Input]: Input[I] } 
  : never
// 输出:type Output2 = [string, number, boolean]

这种方式利用TypeScript对条件类型中泛式元组的处理逻辑,自动排除继承属性,输出纯净的元组类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:13:13