If the type is not important, use unknown
When dealing with a generic operation on an array like moving elements, the specific type of the array is not crucial. You can simply indicate that the function will accept any array using unknown[]
or `Array:
type Foo = number[]
type Bar = string[]
function move(x: unknown[]) {
const v = x.splice(0, 1)
x.splice(1, 0, ...v)
}
declare const arr: Foo | Bar;
move(arr); //OK
Playground Link
Use generics when the type is important
If specifying the type is relevant, use generics and restrict it to arrays:
type Foo = number[]
type Bar = string[]
function move<T extends Array<unknown>>(x: T) {
const v = x.splice(0, 1)
x.splice(1, 0, ...v)
}
declare const arr: Foo | Bar;
move(arr); //OK
Playground Link
This approach can be beneficial to specify expected types in a call, leading to a compilation error if they do not match:
move<string[] | number[]>(arr); // OK
move<string[] | number[] | boolean[]>(arr); // OK
move<string[] | boolean[]>(arr); // error
move<string[]>(arr); // error
Playground Link