I am using helper object to check types of variables. But i have faced a problem with types. I have a generic array: <T, V>(val: V | T[]): val is T[] => R.is(Array, val)
. Using this approach i am trying to avoid using any
. This generic works well until val
can be, for example, string[]
or number[]
.
Example:
const a = (b: string[] | number[] | string ) => {
is.array(b)
}
In this case generic captures only the first possible array type and checks it. I am attaching a link to codesandbox with the illustration of issue. Please, help
CodePudding user response:
Use Array.isArray
:
function f(b: string[] | number[] | string) {
if (Array.isArray(b)) {
// b: string[] | number[]
} else {
// b: string
}
};
Its declaration:
function isArray(arg: any): arg is any[];
Own typeguard implementation:
function isArray(arg: any): arg is any[] {
return arg !== null && typeof arg === "object" && "length" in arg;
}
Rambda solution:
function array(arg: any): arg is any[] {
return R.is(Array, arg);
}