thedayturns thedayturns - 2 months ago 17
TypeScript Question

How to type guard on a 2D array in TypeScript?

I tried to write some code like this:

const x: string[] | string[][] = blah();
if (Array.isArray(x[0])) {
// I expect x to be inferred to be string[][] here, but it's not!
}


How come this doesn't infer
x
to be a 2D array? Am I doing something wrong, or is TypeScript?

Answer

there isn't a ways to type guard those particular unions. That said you can create a custom type guard function quite easily:

/** Custom type guard */
const isArrayArray = (x): x is string[][] => Array.isArray(x[0]);

const x: string[] | string[][] = [];
if (isArrayArray(x)) {
    // x:string[][]
  x;
}

More

user defined guards covered here : https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

Comments