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

TypeScript中如何通过直接键访问与泛型接口正确推断键类型?

TypeScript类型推断问题:泛型映射的类型关联识别失败

我希望TypeScript能在以下场景中正确推断有效类型:

首先定义两个接口/类型:

interface A {
  first: string;
}

type B = {
  second: string;
}

以及一个包含依赖映射的泛型接口:

interface Gen<T extends string> {
  firstMapper: () => T;
  callback(arg: T): string;
}

同时定义记录多个Gen接口的对象类型:

interface Aobject {
  "a": Gen<"a">,
  "b": Gen<"b">,
}

我编写了一个函数,接收Aobject的键,获取对应配置后调用firstMapper和callback:

const buildMapping = (configKey: keyof Aobject, arg: Aobject) => {
  const myA: Aobject = {
    "a": {
      firstMapper: () => "a",
      callback: (input) => ("result" + input)
    },
    "b": {
      firstMapper: () => "b",
      callback: (input) => ("result" + input)
    }
  }

  const selected = myA[configKey];
  selected.callback(selected.firstMapper());
}

此时TypeScript抛出错误:

Argument of type 'string' is not assignable to parameter of type 'never'.
Type 'string' is not assignable to type 'never'.

但改用分支判断则不会报错:

if (configKey === "a") {
  const selected = myA[configKey]
  selected.callback(selected.firstMapper())
}
if (configKey === "b") {
  const selected = myA[configKey]
  selected.callback(selected.firstMapper())
}

我的理解是:TypeScript无法识别configKey的类型与selected类型的对应关系,会将callback的参数推断为"a"和"b"的交集,即never类型。我希望找到无需重复分支代码的解决方案,尝试过泛型接口优化但未成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:50:28