网站搜索

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


有这样一个问答,它帮助提供了一种简明的方法来定义命名箭头函数的形状,但没有涉及匿名内联函数:在 TypeScript 箭头函数中指定返回类型

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

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[]是否是唯一的方法?

答案#1

另一问题的答案中的解决方案在这里也适用。即使是匿名箭头函数,也允许你在参数列表的右括号之后、箭头之前用冒号标注返回类型,如下所示:

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

你可以验证这是否按预期工作:

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

// const otherTypeArr: OtherType[]

代码的 Playground 链接

答案#2

你可以为 array.map<T>() 提供一个通用类型参数,如下所示:

TS Playground 链接

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