简体   繁体   中英

TypeScript fundamentals: generics and arrow functions

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!

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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM