这个问题和答案有助于提供一种简洁的方法来定义 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[]
关于typescript - 如何指定 TypeScript 匿名内联箭头函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70050926/