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
});
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
});
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
});
=>
an {
is always interpreted as a code block, no exceptions. But after =>
we can have any expression, including a parenthesis expression (...)
and inside this new expression we can have an object literal, but the (...)
does not in any other way change the meaning of the object expression. The type assertion <IKey>
serves a similar function, it will introduce a new type of expression after the =>
instead of having the {
which always means code block. Hope this makes it a bit more clear
Jun 20, 2019 at 12:50
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:
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.
interface
. As long as you don't try to use key3
, it will be type-safe. I would argue that key3
would be a bit like some unknown prototype. property.
None of the above options have worked for me with React's TSX files.
This is the code that worked for me:
interface IKeys { key1: string; key2: string }
array.map((val: any): IKeys => ({
key1: val.key1,
key2: val.key2
}));