I want to use an interface with generic union types like this:
interface IOperator {
<U>(a: U[], b: U[] | U): boolean
}
export const intersects: IOperator = (a, b) => a.some((el) => b.includes(el))
export const includes: IOperator = (a, b) => a.includes(b)
However, TS gives me error on both regarding one of the union types:
Property 'includes' does not exist on type 'U | U[]'.
Property 'includes' does not exist on type 'U'.
How do I typecast properly here?
I tried:
export const intersects: IOperator = (a, b) => a.some((el) => (b as U[]).includes(el))
However, that gives me an error:
Cannot find name 'U'.
So how to handle generic union types?
I know that for the intersects method the types for input b should only be arrays and for the includes method the types for input b should never be arrays. The idea for the interface is to not repeat myself as I have plenty of methods where some require b to be an array and others to not be an array. I'd try to avoid to create two separate interfaces.
Thank you!
bisUnot an array ofU, it (probably) won't have anincludesmethod.bis an array.