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

如何让TypeScript Record中每个值拥有独立泛型类型?

解决TypeScript RouteMap条目独立泛型参数的问题

要让RouteMap中每个Route条目拥有独立的泛型参数,而非统一使用any,你需要将RouteMap定义为泛型类型,通过泛型参数映射每个路由条目的具体类型。

步骤1:定义泛型RouteMap类型

将RouteMap改为接受一个泛型参数,该参数描述每个路由条目对应的泛型类型结构:

// 假设你的Route泛型类型定义如下(根据实际情况调整)
type Route<T> = {
  path: string;
  // 示例handler,可替换为你的实际属性(比如component)
  handler: (data: T) => void;
};

// 泛型RouteMap:每个键对应Route<对应类型>
export type RouteMap<T extends Record<string, unknown>> = {
  [K in keyof T]: Route<T[K]>;
};

步骤2:使用时自动推断类型

你可以直接指定泛型参数,或者通过辅助函数让TypeScript自动推断每个条目的类型:

方式1:显式指定泛型参数

const routes: RouteMap<{
  home: { userId: number };
  profile: { username: string; bio: string };
}> = {
  home: {
    path: "/home",
    handler: (data) => {
      // data自动推断为{ userId: number }
      console.log(data.userId);
    },
  },
  profile: {
    path: "/profile",
    handler: (data) => {
      // data自动推断为{ username: string; bio: string }
      console.log(data.username, data.bio);
    },
  },
};

方式2:用辅助函数自动推断

如果不想手动写泛型参数,可创建一个辅助函数让TypeScript自动推导类型:

function createRouteMap<T extends Record<string, unknown>>(routes: RouteMap<T>) {
  return routes;
}

// 自动推断每个Route的泛型类型
const routes = createRouteMap({
  home: {
    path: "/home",
    handler: (data) => {
      console.log(data.userId); // data类型自动推断为{ userId: number }
    },
  },
  profile: {
    path: "/profile",
    handler: (data) => {
      console.log(data.username); // data类型自动推断为{ username: string; bio: string }
    },
  },
});

为什么原来的写法不行?

原来的[k in string]: Route<any>是索引签名,强制所有路由条目都为Route<any>,丢失了每个条目的具体类型信息。而泛型RouteMap<T>通过映射keyof T到Route<T[K]>,让每个条目可以绑定独立的泛型参数,TypeScript能根据实际传入的路由对象自动推断出每个条目的类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:18:25