Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading