Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 434
Fay Chen Avatar asked Apr 11 '26 11:04

Fay Chen


1 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'}));
like image 104
axtck Avatar answered Apr 13 '26 00:04

axtck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!