thedayturns thedayturns - 1 year ago 142
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?

Answer Source

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 :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download