I am dealing with various types and their unions.
Here is the code snippet:
type A = {
name: string
}
type B = {
work: boolean
}
type AB = A[] | B[]
const func = (): AB => {
return [{ name: 'ww' }]
}
const data = func()
My goal is to pass a parameter of union type to a generic function.
export const randomGenericFunction = <O, T extends Record<string, unknown>>(
param1: O,
param2: T[]
) => {
...
const d = param2.map(p => p)
...
}
However, when I try passing it like this:
randomGenericFunction('param1', data)
An error occurs:
Argument of type 'AB' is not assignable to parameter of type 'A[]'.
Type 'B[]' is not assignable to type 'A[]'.
Property 'name' is missing in type 'B' but required in type 'A'.
Upon hovering over the randomGenericFunction
call, I notice that it is treating T
as A[]
instead of AB
.
My assumption is that this issue stems from the fact that T
is not recognized as a union type, causing it to only recognize the first type in the union. How can I properly type the T
parameter in the generic function as a union in this scenario?