Typescript Array Map Return Object

Typescript

Typescript Problem Overview


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

Typescript Solutions


Solution 1 - Typescript

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

Solution 2 - Typescript

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.

Solution 3 - Typescript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan GrahnView Question on Stackoverflow
Solution 1 - TypescriptTitian Cernicova-DragomirView Answer on Stackoverflow
Solution 2 - TypescriptellockieView Answer on Stackoverflow
Solution 3 - TypescriptkurtkoView Answer on Stackoverflow