Home > Enterprise >  Differentiate between SomeType[] and SomeType[][] (1-dimensional vs 2-dimensional array type)
Differentiate between SomeType[] and SomeType[][] (1-dimensional vs 2-dimensional array type)

Time:09-23

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[]
    }
}

Playground


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]);
  • Related