Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
add extra property type in map typescript
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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'}));
about 4 years ago · Juan Pablo Isaza Report

0

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).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!