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

TypeScript联合类型索引报隐式any 如何不用分支用泛型解决?

错误原因

TypeScript 目前无法自动推导联合类型中两个关联字段的对应关系,当你同时用m.type和m.method两个联合字段做嵌套索引时,TS只会将两个字段的联合类型直接展开组合,不会判断type为'a'时method只能是'foo'|'bar',因此会抛出索引不匹配的错误。


泛型解决方案

你可以通过以下泛型实现解决问题,既不需要冗余的分支判断,也能保证类型安全:

type ModelA = {
    type: 'a'
    method: 'foo' | 'bar'
}

type ModelB = {
    type: 'b'
    method: 'baz'
}

type Model = ModelA | ModelB

const dictionary = {
    a: {
        foo: () => 'foo',
        bar: () => 'bar'
    },
    b: {
        baz: () => 'baz'
    }
}

// 方案1:直接基于dictionary类型做泛型约束
type Dictionary = typeof dictionary;
function getMethod<T extends keyof Dictionary>(m: {
  type: T;
  method: keyof Dictionary[T];
}) {
  return dictionary[m.type][m.method];
}

// 方案2:复用上文已定义的Model类型
function getMethod<T extends Model['type']>(m: Extract<Model, {type: T}>) {
  return dictionary[m.type][m.method];
}

以上实现会在调用时自动推导传入参数的type,并约束method只能是对应type下的合法值,既解决了编译报错,也保留了完整的类型校验能力。

如果不需要严格的入参类型校验,也可以用类型断言快速解决:

function getMethod(m: Model) {
  return (dictionary[m.type] as Record<string, Function>)[m.method];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:42:02