I'm trying to write some generic array utility functions, but when I try calling one from another, the compiler seems to cast the generic to any[] and gives me this error:
Type 'any[]' is not assignable to type 'T'.
My code:
type UnwrapArray<T extends any[]> = T extends (infer G)[] ? G : never;
function removeFromArray<T extends any[]>(
array: T,
value: UnwrapArray<T>
) {
return array.filter(other => other !== value);
}
function toggleArrayValue<T extends any[]>(array: T, value: UnwrapArray<T>): T {
if(array.includes(value)) {
return removeFromArray<T>(array, value);
} else {
return [...array, value];
}
}
The specific lines giving me trouble are these:
return removeFromArray<T>(array, value);
And
return [...array, value];
I've found I can add as T to a bunch of stuff and it will compile successfully, but it seems like the compiler should figure this out on its own.