【发布时间】: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