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

问题描述 投票:0回答:1

下面的示例函数

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);
typescript
1个回答
0
投票
  1. 您的函数
    myFunction
    返回另一个接受回调的函数。此回调应使用指定的泛型类型
    T
    U
    作为其参数:
return (functionArgument: (argumentOne: T, argumentTwo: U) => void) => {...}
  1. 调用
    myDesiredFunction
    时,您应该显式设置
    T
    U
    :
const myDesiredTest = myDesiredFunction<TypeOne, TypeTwoExtended>({key: "test"})((argumentOne, argumentTwo) => null)
© www.soinside.com 2019 - 2024. All rights reserved.