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

TypeScript映射元组提取成员value类型报错及readonly元组兼容问题

问题解决方案

原因说明

  • 第一个报错Type '"value"' cannot be used to index type 'T[Index]':遍历keyof T时,除了元组的数字索引,还会包含数组类型的内置属性(如length、map等),这些属性对应的类型不包含value字段,无法直接索引。
  • 第二个只读元组不兼容报错:as const断言生成的是带readonly修饰的只读元组,原泛型约束Argument[]仅支持可变数组,类型不匹配。

修复代码

export type Argument<T = unknown> = {
  value: T;
};

// 泛型约束新增readonly支持,同时用条件类型推导value类型避免索引报错
export type TypesOf<T extends readonly Argument[]> = {
  [Index in keyof T]: T[Index] extends Argument<infer ValueType> ? ValueType : never
};

验证效果

普通元组场景

// 类型为 [number, string],符合预期
type Test1 = TypesOf<[{value: number}, {value: string}]>

const断言只读元组场景

const tuple = [{value: 1}, {value:"foo"}] as const;
// 类型为 readonly [1, "foo"],无报错
type V = TypesOf<typeof tuple>;

如果需要得到可变元组类型,可以额外添加Mutable类型去除readonly修饰:

type Mutable<T> = { -readonly [P in keyof T]: T[P] };
// 类型为 [1, "foo"]
type MutableV = Mutable<TypesOf<typeof tuple>>;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:45:01