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

TypeScript动态函数参数类型匹配错误问题求助

TypeScript动态函数参数类型匹配问题

我需要实现一个基于映射对象的动态函数,根据不同的键匹配对应的输入参数类型,但当前代码出现了类型错误。

示例代码

interface InputA {
    id: string
    test: string
}

interface InputB {
    param: string
    somethingElse: string
}

type ReturnType = Record<string, string | number | boolean>

export interface IFunctionMapper {
  A: (values: InputA) => ReturnType
  B: (values: InputB) => ReturnType
}

/**
 * Transforms params into output
 */
const FunctionMapper: IFunctionMapper = {
  A: (params) => {
    return { id: params.id }
  },
  B: (params) => {
    return { myProperty : params.somethingElse }
  },
} as const

type Keys = keyof typeof FunctionMapper
type Params = Parameters<typeof FunctionMapper[Keys]>[0]

/**
 * Get output using mapping function
 */
function getOutput(name: keyof typeof FunctionMapper, params: Params){
    const fn = FunctionMapper[name]
    return fn(params)
}

出现的类型错误

Argument of type 'InputA | InputB' is not assignable to parameter of type 'InputA & InputB'.

问题原因

TypeScript无法自动推断name和params之间的类型关联——它认为fn可能是A或B对应的任意函数,而params是InputA | InputB的联合类型,因此会要求参数必须同时满足InputA和InputB的交叉类型,导致报错。

解决方案

使用泛型绑定name和params的类型关联,让TypeScript明确每个键对应的参数类型:

修改后的getOutput函数:

function getOutput<K extends keyof typeof FunctionMapper>(
  name: K, 
  params: Parameters<typeof FunctionMapper[K]>[0]
){
    const fn = FunctionMapper[name]
    return fn(params)
}

完整修改后代码

interface InputA {
    id: string
    test: string
}

interface InputB {
    param: string
    somethingElse: string
}

type ReturnType = Record<string, string | number | boolean>

export interface IFunctionMapper {
  A: (values: InputA) => ReturnType
  B: (values: InputB) => ReturnType
}

/**
 * Transforms params into output
 */
const FunctionMapper: IFunctionMapper = {
  A: (params) => {
    return { id: params.id }
  },
  B: (params) => {
    return { myProperty : params.somethingElse }
  },
} as const

/**
 * Get output using mapping function
 */
function getOutput<K extends keyof typeof FunctionMapper>(
  name: K, 
  params: Parameters<typeof FunctionMapper[K]>[0]
){
    const fn = FunctionMapper[name]
    return fn(params)
}

修改后,调用getOutput('A', { id: '1', test: 'test' })或getOutput('B', { param: '2', somethingElse: 'else' })时,TypeScript会自动校验参数类型是否匹配,不会再出现类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:10:00