Search code examples
typescripttypescript-types

Typescript: How type a function using generic type in this case?


I have this type definition

type FuncType<T> = (value: T) => T

I want to implement a function using this type that would look like:

const myFunc: FuncType<T> = (value) => value;

and use it as follows:

const a: string = myFunc<string>('a');
const b: number = myFunc<number>(2);

But, of course, the previous line const myFunc: FuncType<T> = (value) => value; doesn't have a valid syntax.

How should it be written ?


Note: I found a workaround using an intermediate function but it would be nice to avoid this useless currying (that I cannot use anyway in my real use case because it's related to react hook and react hooks doesn't tolerate currying):

const myFunc = <T>(): FuncType<T> => (value) => value;
const a: string = myFunc<string>()('a');
const b: number = myFunc<number>()(2);


Why do I need to use this type alias and cannot directly write ?

const myFunc = <T>(value: T): T => value;

Because in my real use case, the type definition of my function is not that simple.

It looks like something like that:

interface FuncType<T> {
  (args: {arg1: T}): {res1: T}
  (args: {arg1: T, arg2: T}): {res1: T, res2: T}
}

Solution

  • So far I don't see a use case for FuncType being a generic type alias to a concrete overloaded function. Could you instead make it a concrete type alias to a generic overloaded function? Like this:

    interface FuncType {
      <T>(args: { arg1: T }): { res1: T }
      <T>(args: { arg1: T, arg2: T }): { res1: T, res2: T }
    }
    

    Then FuncType will always refer to something that accepts any T, and you can use it the way you wanted:

    const myFunc: FuncType =
      (value: { arg1: any, arg2?: any }) => ({ res1: value.arg1, res2: value.arg2 });
    
    const a = myFunc<string>({ arg1: "" }); // { res1: string; }
    const b = myFunc<number>({ arg1: 1, arg2: 2 }); // { res1: number; res2: number; }
    

    Hopefully that meets your needs. Good luck!

    Link to code