typescript 打字稿数组映射返回对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47755247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript Array Map Return Object
提问by Dan Grahn
I have the following code.
我有以下代码。
array.map(val => { return {
key1: val.key1,
key2: val.key2
}});
Is there any way to reduce the code to something like this?
有没有办法将代码减少到这样的程度?
array.map(val => {
key1: val.key1,
key2: val.key2
});
回答by Titian Cernicova-Dragomir
If you put it in parenthesis the compiler will treat it as an object literal not a code block:
如果将它放在括号中,编译器会将其视为对象文字而不是代码块:
array.map(val => ({
key1: val.key1,
key2: val.key2
}));
A type assertion also works if you have an interface for the object literal (but is not as type safe):
如果您有对象文字的接口(但不是类型安全的),则类型断言也有效:
interface IKeys { key1: string; key2: string }
array.map(val => <IKeys>{
key1: val.key1,
key2: val.key2
});
回答by ellockie
As an update to @Titian Cernicova-Dragomir's answer above, it's worth mentioning the as
operator(for Type Assertion), especially useful when working with React's TSX(JSX) files, equivalent to the <Type>
syntax:
作为上面@Titian Cernicova-Dragomir 回答的更新,值得一提的是as
操作符(用于类型断言),在处理 React 的 TSX(JSX) 文件时特别有用,相当于<Type>
语法:
interface IKeys { key1: string; key2: string }
// notice the parentheses, to avoid confusion with a block scope
array.map(val => ({
key1: val.key1,
key2: val.key2
} as IKeys));
It was introduced because the angle brackets syntax (<ComponentOrElement>
) is reserved for components / JSX Elements.
引入它是因为尖括号语法 ( <ComponentOrElement>
) 是为组件/ JSX 元素保留的。