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

如何从参数推断第一个泛型函数类型并指定第二个?

解决方案

你需要调整泛型的声明逻辑,让需要用户显式指定的第二个参数类型可单独传入,同时让第一个参数的类型由传入的参数自动推断,以下是两种可行实现方式:

方法一:调整泛型顺序

把需要用户指定的泛型U放在第一位,让T通过传入的参数自动推断:

interface TypeOne {
    key: string;
}

interface TypeTwo {
    value: string;
}

interface TypeTwoExtended extends TypeTwo {
    secondValue: string;
}

const myDesiredFunction = <U extends TypeTwo, const T extends TypeOne>(parameter: T) => { 
    return (functionArgument: (argumentOne: T, argumentTwo: U) => null) => {
        console.log(functionArgument);
    }
}

// argumentOne自动推断为{ key: "test" }(兼容TypeOne),argumentTwo为TypeTwoExtended
const myDesiredTest = myDesiredFunction<TypeTwoExtended>({key: "test"})((argumentOne, argumentTwo) => null);

补充说明

  • 若希望argumentOne严格匹配TypeOne而非更具体的子类型,将函数内的argumentOne: T改为argumentOne: TypeOne即可。

方法二:柯里化拆分泛型(逻辑更清晰)

把函数拆分为两步,先指定第二个参数的类型,再传入参数让TS自动推断第一个参数的类型:

const myDesiredFunction = <U extends TypeTwo>() => {
    return <const T extends TypeOne>(parameter: T) => {
        return (functionArgument: (argumentOne: T, argumentTwo: U) => null) => {
            console.log(functionArgument);
        }
    }
}

// 调用逻辑:先指定U类型 → 传入参数推断T → 传入目标函数
const myDesiredTest = myDesiredFunction<TypeTwoExtended>()({key: "test"})((argumentOne, argumentTwo) => null);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:46:03