Typescript Array Map Return Object

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.


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

Tags:

Typescript