0

this has an error:

interface TypeA {
  prop1: string
}
interface TypeB extends TypeA {
  prop2: string
}
const ArrA: TypeA[] = [{ prop1: "foo" }]
const ArrB: TypeB[] = ArrA.map(a => {
  a.prop2 = "bar"
  return a
})

this gets an error: [ts] Property 'prop2' does not exist on type 'TypeA'.

and i want to do this without using any in my interface definitions (like in this Stackoverflow question from 5 years ago). I can't find any other solution on Stackoverflow so I am posing this question here.

swyx
  • 2,378
  • 5
  • 24
  • 39

2 Answers2

1

How about this:

const ArrB: TypeB[] = ArrA.map(a => {
  return {
    ...a,
    prop2: "bar"
  }
})
Aaron Beall
  • 49,769
  • 26
  • 85
  • 103
0

I need to use the as keyword for casting and also add prop2 as an optional param on TypeA:

interface TypeA {
  prop1: string;
  prop2?: string;
}
interface TypeB extends TypeA {
  prop2: string;
}
const ArrA: TypeA[] = [{ prop1: "foo" }];
const ArrB: TypeB[] = ArrA.map(a => {
  a.prop2 = "bar";
  return a as TypeB;
});

this is the best solution i could find, would appreciate more idiomatic solutions that 1) dont involve modifying TypeA, and 2) dont involve the use of any. Thank you.

swyx
  • 2,378
  • 5
  • 24
  • 39