someFunction(someParameter: SomeType[] | SomeType[][]) {
// ...
}
In the function body how would I differentiate between the 2 possible array types of someParameter?
CodePudding user response:
You probably need a type predicate:
function isMatrix(value: any): value is any[][] {
return Array.isArray(value[0]);
}
function someFunction(someParameter: SomeType[] | SomeType[][]) {
if (isMatrix(someParameter)) {
someParameter
// ^? SomeType[][]
} else {
someParameter
// ^? SomeType[]
}
}
If you want an empty array to be interpreted as a matrix, you can change the return in the type guard to this:
return !value.length || Array.isArray(value[0]);