add extra property type in map typescript

Viewed 467
const x = [{a: 1, b: 2}].map((d: any) => ({...d, c: 'something new'}))

how can I make x has c property on array of object above?

I tried

const x = ([{a: 1, b: 2}] as any).map((d: <{c: string}>) => ({...d, c: 'something new'})) but it doesn't seems it's the right syntax.

2 Answers

You don't need the <> when specifying an inline type

const x = ([{a: 1, b: 2}] as any).map((d: {c: string}) => ({...d, c: 'something new'}))

You could type the result like this

const x: Array<{a:number; b: number; c:string;}> = [{a: 1, b: 2}].map((d) => ({...d, c: 'something new'}))

Or simply let TypeScript figure it out (preferred as @AluanHaddad mentioned)

const x = [{a: 1, b: 2}].map((d) => ({...d, c: 'something new'}));

Sometimes it helps to name and annotate the types you want to figure out what's needed.

interface AB {
  a: number
  b: number
}

interface ABC extends AB {
  c: string
}

const x: ABC[]                      // annotate what's expected
  = [{a: 1, b: 2}]                  // input
  .map(
    ab =>                           // inferred type
    ({...ab, c: 'something new'})   // result is shape of ABC (per element)
  )

// Once more, allowing type inference to do the work
// just to show we can be succinct when we want to be
const y = [{ a: 1, b: 2 }].map(ab => ({...ab, c: 'something'}))
//    ^ NB: y is not typed as ABC[], but has the right shape

Personally I often like to specify the type on the receiving variable (const x: ABC[] ...) because this ensures that the result it the shape we expect (and if we hover over later, will show that type, not something that happens to be the right shape which might be hard to grok).

Related