下面的示例函数
myDesiredFunction
返回一个以函数 X 作为参数的函数。函数 X 应采用两个参数。第一个参数的类型应该从传递给 myDesiredFunction
的参数中推断出来。第二个参数应该能够通过传递给 myDesiredFunction
的泛型类型来指定。我怎样才能实现这个目标?
interface TypeOne {
key: string;
}
interface TypeTwo {
value: string;
}
// how far I got
const myFunction = <const T extends TypeOne>(parameter: T) => {
// I don't want to have to define TypeTwo here explicitly, but when the user calls this function
return (functionArgument: (argumentOne: TypeOne, argumentTwo: TypeTwo) => null) => {
console.log(functionArgument);
}
}
const myTest = myFunction({key: "test"})((argumentOne, argumentTwo) => null);
// what I'd like
interface TypeTwoExtended extends TypeTwo {
secondValue: string;
}
const myDesiredFunction = <const T extends TypeOne, U extends TypeTwo>(parameter: T) => {
return (functionArgument: (argumentOne: TypeOne, argumentTwo: U) => null) => {
console.log(functionArgument);
}
}
// argumentOne should be of type TypeOne, and argumentTwo should be of type TypeTwoExtended
const myDesiredTest = myDesiredFunction<TypeTwoExtended>({key: "test"})((argumentOne, argumentTwo) => null);
myFunction
返回另一个接受回调的函数。此回调应使用指定的泛型类型 T
和 U
作为其参数:return (functionArgument: (argumentOne: T, argumentTwo: U) => void) => {...}
myDesiredFunction
时,您应该显式设置 T
和 U
:const myDesiredTest = myDesiredFunction<TypeOne, TypeTwoExtended>({key: "test"})((argumentOne, argumentTwo) => null)