I want to map over union of arrays, how can I make it type safely?
I have a solution, but I want to avoid hard-coding the types from the type union.
When calculating newArr1
, as expected, I get an error: Property 'field2' does not exist on type 'Common<A, B>'
Is there a way to get the same error when calculating newArr2
?
interface A {
field1: string
field2: number
}
interface B {
field1: string
}
type Common<A, B> = {
[P in keyof A & keyof B]: A[P] | B[P];
}
function mapArray(arr: A[] | B[]) {
const newArr1 = (arr as Common<A, B>[]).map(i => i.field2) // error
// how can I get the same error without hard-coding the types from the type union?
const newArr2 = (arr as MagicEventuallyFromJcalz<typeof arr>).map(i => i.field2)
return newArr1
}