typescript - 如何指定 TypeScript 匿名内联箭头函数的返回类型

标签 typescript types

这个问题和答案有助于提供一种简洁的方法来定义 NAMED 箭头函数的形状,但不涉及匿名内联函数: 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[] 是唯一的方法吗?

最佳答案

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

关于typescript - 如何指定 TypeScript 匿名内联箭头函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70050926/

相关文章:

javascript - index.js 没有做 index.ts 做的事情

typescript - 如何隐藏和替换 Angular2 中的组件

typescript - 使用 --noEmit 时使用 TypeScript 进行增量编译?

cocoa - Cocoa 中有类似 [aCalCalendar setType] 的东西吗?

c++ - 如何在 C++ 中通过 'int' 类型 'vector<int>' 来决定?

c++ 使用子类 'type cast' 错误

arrays - 使用 TypeScript 将数组传递给扩展运算符参数

javascript - 在 Typescript 中封装 WebSocket 消息

javascript - 动态键类型与 typescript 中的其他键类型

typescript 覆盖子类中的重载方法 - 类型不正确