Home > Software design >  Type signature for generic function whose argument has a different type than output
Type signature for generic function whose argument has a different type than output

Time:09-10

Hi I'm trying to pass in a function as an argument to another function and in doing so need to provide the type signature for that function. I thought this would do the trick:

const funct1 = (obj1: Object, funct2: <T, K>(a:T) => K, obj2: any) => {
    ///...
}

However when I call it with something like this:

const convertFromDate = (obj: Date) : number => {
  return obj.valueOf() / 1000;
};

funct1(d1, convertFromDate, Date) // error: Type 'number' is not assignable to type 'K'. 
                                  //'number' is assignable to the constraint of type 'K',
                                  // but 'K' could be instantiated with a different subtype of constraint 'unknown'.

I got the above error. How should I define the type signature of a function that takes an argument of one type and returns another?

CodePudding user response:

wasn't sure what you wanted to do with obj2 in funct1. But the understanding is that you want func1 to take a func as a param, and an object that is this functions arguments. Then returns the execution of func(obj1)

type FunctionReturnType<T> = T extends (...args: any) => infer R ? R : T;
const funct1 = <T,K extends (obj: T) => any>(obj1: T, func2:K):FunctionReturnType<K> => {
    return func2(obj1);
}

const d1 = new Date()
const convertFromDate = (obj: Date) : number => {
  return obj.getTime();
};

const s = funct1<Date,typeof convertFromDate>(d1, convertFromDate) //type:number
console.log(s) //Log 166270725578...
  • Related