thedayturns thedayturns - 5 months ago 54
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
to be a 2D array? Am I doing something wrong, or is TypeScript?


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


user defined guards covered here :