繁体   English   中英

TypeScript 基础知识:generics 和箭头函数

[英]TypeScript fundamentals: generics and arrow functions

我正在阅读 TypeScript 手册,并试图转换以下内容:

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

到箭头 function。 所以我这样做了,我认为这是正确的:

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

但是我想知道如果我想像这样为 function 使用类型别名,我将如何实现它:

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

由于Output[],上面的这个例子产生了一个错误。 那么,由于Output[]将不再起作用,我将如何定义map2的 output 类型? 任何帮助将不胜感激!

我们不能以您描述的确切方式使用Fn ,我们需要以允许我们在使用类型时传入 generics 的方式定义Fn 像这样:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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