2

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}
}
3
  • Do you really need the type alias? Maybe you could just function myFunc<T>(value: T) : T { return value; } Commented Oct 31, 2019 at 16:17
  • @AlekseyL. I updated my question to answer to yours. Commented Oct 31, 2019 at 16:29
  • The question is: are you using the type in multiple places? If yes, please show the use case. Otherwise my suggestion is still valid - add as many overloads as needed Commented Nov 1, 2019 at 3:34

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

To sum up, simply change from

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

to

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.