Typescript Array Map Return Object

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

Leave a Comment