I'm trying to define a function includes, that works for both, arrays and strings.
But I'm having trouble typing it correctly. If I understand correctly, overloading is possible using unions. So this is what I'm trying:
// Declarations
export function includes<T>(arr: T[], el: T): boolean;
export function includes(str: string, substr: string): boolean;
// Implementation
export function includes<T>(arr: T[] | string, el: T | string) {
return arr.indexOf(el) !== -1;
}
But I'm getting the error:
'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype
which makes sense, because if arr is of type T, el shouldn't be of type string, but the unions makes that a "possibility".
So how would I correctly type the implementation here to say that the arguments may be either T[] and T or string and string?
elasanyin the implementation. It's not part of your public API anyway.Tin case 1 andstringin case 2, then I'd want to keep the type safety. So then I'd have to type it correctly. How would I do thatfunction includes<T>(a: T extends string ? string : T[], b: T): boolean ...