Home > Enterprise >  TypeScript fundamentals: generics and arrow functions
TypeScript fundamentals: generics and arrow functions

Time:12-08

I was going through the TypeScript handbook and was attempting to convert the following:

function map<Input, Output>(
  arr: Input[],
  func: (arg: Input) => Output
): Output[] {
  return arr.map(func);
}

to an arrow function. So I did this, which I think is correct:

const map2 = <Input, Output>(
  arr: Input[],
  func: (arg: Input) => Output
): Output[] => {
  return arr.map(func);
};

But I was wondering how I'd implement it if I wanted to use a type alias for the function like this:

type Fn = <X, Y>(x: X) => Y;
const map2 = <Input, Output>(
  arr: Input[],
  func: Fn 
): Output[] => {
  return arr.map(func);
};

This example above yields an error because of Output[]. So how would I define the output type of map2 since Output[] will no longer work? Any help would be deeply appreciated!

CodePudding user response:

We can't use Fn in the exact way you've described, we need to define Fn in such a way that allows us to pass in our generics when we use the type. Like this:

type Fn<X, Y> = (x: X) => Y;

const map2 = <Input, Output>(
  arr: Input[],
  func: Fn<Input, Output>
): Output[] => {
  return arr.map(func);
};
  • Related