【问题标题】:How to specify return type for TypeScript anonymous inline arrow function如何为 TypeScript 匿名内联箭头函数指定返回类型
【发布时间】:2021-12-31 04:15:30
【问题描述】:

有这个问题和答案有助于提供一种简洁的方式来定义命名箭头函数的形状,但不涉及匿名内联函数: Specify return type in TypeScript arrow function

我想使用简单的内联匿名箭头函数将一种对象类型映射到另一种对象类型:

type MyType = {
    foo: string
};
type OtherType = {
    bar: string
};

const myTypeArr: MyType[] = [{foo: 'abc'}, {foo: 'qwe'}];

// note the anonymous inline arrow function below
const otherTypeArr: OtherType[] = myTypeArr.map(o => ({bar: o.foo}));

编译器似乎将其视为有效代码。如果我这样做会引发错误:

// Error: Property 'baz' does not exist on type 'MyType'.
const otherTypeArr: OtherType[] = myTypeArr.map(o => ({bar: o.baz}));
// Error: Property 'bar' is missing in type '{ baz: string; }' but required in type 'OtherType'
const otherTypeArr: OtherType[] = myTypeArr.map(o => ({baz: o.foo}));

但我相信它是在推断匿名函数中的类型。有没有办法明确指定输入类型和返回类型?

我想我可以像这样轻松地指定输入类型:

const otherTypeArr: OtherType[] = myTypeArr.map((o: MyType) => ({bar: o.foo}));

但我仍然看不到手动指定函数返回类型的方法。我已经在变量中指定OtherType[] 是唯一的方法吗?

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    answer to the other question 中的解决方案也适用于此。甚至匿名箭头函数也允许您在参数列表的右括号之后和箭头之前用冒号注释返回类型,如下所示:

    (o: MyType): OtherType => ({ bar: o.foo })
    //         ^^^^^^^^^^^ <-- return type annotation
    

    您可以验证这是否按要求工作:

    const otherTypeArr =
        myTypeArr.map((o: MyType): OtherType => ({ bar: o.foo }));
    
    // const otherTypeArr: OtherType[]
    

    Playground link to code

    【讨论】:

    • 我想这就是我想要的。但我也喜欢另一个答案的干净。指定两者可能会有点矫枉过正,而另一个答案更适合链式地图/功能:const anotherArr = o.map&lt;SomeType&gt;(a =&gt; b).map&lt;OtherType&gt;(b =&gt; c).map&lt;AnotherType&gt;(c =&gt; d);
    【解决方案2】:

    您可以向array.map&lt;T&gt;() 提供一个泛型类型参数,如下所示:

    TS Playground link

    // variable is annotated
    const otherTypeArr1: OtherType[] = myTypeArr.map(o => ({bar: o.foo}));
    
    // return type of callback function is specified in generic type arguent to array.map
    const otherTypeArr2 = myTypeArr.map<OtherType>(o => ({bar: o.foo}));
    

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 2022-01-22
      • 2012-11-06
      • 2018-01-25
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2019-10-06
      • 2021-12-15
      相关资源
      最近更新 更多