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

如何从具体字符串推断其匹配的TypeScript泛型键类型?

解决方案:从具体字符串反向推断模板字符串索引类型

要实现从具体字符串反向匹配并返回对应的模板字符串索引类型,核心思路是遍历目标类型的所有键模板,找到能包含该具体字符串的那个模板类型。

实现代码

type Foo = {
  [x: `/tea/${string}/cup`]: void;
  [x: `/coffee/${string}/time`]: void;
  [x: `/cake/${string}/tin`]: void;
}

type MatchesFooKey<T extends string> = T extends keyof Foo ? true : false;
type TestMatch = MatchesFooKey<'/coffee/123/time'>; // 正确返回true

// 正确的反向推断类型
type InferFooKey<T extends string> = keyof Foo extends infer K 
  ? K extends string 
    ? T extends K 
      ? K 
      : never 
    : never 
  : never;

type TestInfer = InferFooKey<'/coffee/123/time'>; // 返回 `/coffee/${string}/time`
type TestInferTea = InferFooKey<'/tea/matcha/cup'>; // 返回 `/tea/${string}/cup`
type TestInferCake = InferFooKey<'/cake/chocolate/tin'>; // 返回 `/cake/${string}/tin`

原理说明

  1. 提取键模板联合:通过keyof Foo extends infer K获取Foo所有模板字符串键的联合类型(即/tea/${string}/cup | /coffee/${string}/time | /cake/${string}/tin)。
  2. 分发联合判断:利用TypeScript的分布式条件类型特性,遍历联合类型中的每个模板成员,检查输入的具体字符串T是否能赋值给当前模板成员。
  3. 返回匹配模板:找到匹配的模板类型后直接返回,即可得到对应的宽泛模板字符串类型。

原写法T extends (infer R extends keyof Foo)无效的原因是:TypeScript的类型推断默认是从具体值到泛型的正向推断,这里R会被推断为T本身的具体字符串,而非对应的模板类型。通过遍历键模板联合并反向匹配,就能实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:05:21