如何从参数推断第一个泛型函数类型并指定第二个?
解决方案
你需要调整泛型的声明逻辑,让需要用户显式指定的第二个参数类型可单独传入,同时让第一个参数的类型由传入的参数自动推断,以下是两种可行实现方式:
方法一:调整泛型顺序
把需要用户指定的泛型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
相关产品推荐
相关产品推荐

