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

TypeScript调用Map.set等泛型Map函数时能否保留泛型索引?

在调用Map.set时保留TypeScript泛型索引的可行性

问题背景

已定义以下类型:

type DataKind = "string" | "number";

type MapsByKind = {
  string: Map<number, string>;
  number: Map<number, number>;
};

type ValueByKind = {
  string: string;
  number: number;
};

同时定义泛型更新类型:

type UpdatePayload<T extends DataKind> = { readonly id: number; value: ValueByKind[T] };

需要实现一个将上述更新应用到指定Map的函数,但按如下方式定义时,.set方法的泛型会被当作联合类型处理,失去原本的泛型特性:

const applyUpdate = <T extends DataKind>(
  state: MapsByKind[T],
  payload: UpdatePayload<T>
) => {
  const {id,value}=payload;
  state // 类型为MapsByKind[T]
  const setter = state.set // 此处不再是泛型,而是联合类型
  const next = state.set(id,value) // 类型推断为交叉类型
};

结论与替代方案

目前TypeScript暂不支持该场景下保留Map方法的泛型特性,建议改用Record类型的对象替代Map实现类似功能。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:34:58