0

Why doesn't the given code compile, and how do I fix it:

function f(x: string[] | string[][]): string[][] {
  return Array.isArray(x[0]) ? x : [x];
}

As far as I can tell, the return value will always be string[][] since of x is string[], x[0] will not be an array, and if x is string[][] then x[0] will be an array.

Even though, typescript doesn't recognize this and throws an array.
Is there a way to get around it without casting? How?

1 Answer 1

2

Type predicates will narrow the type of x to string[][].

function isMatrix(v: any[] | any[][]): v is any[][] {
    return Array.isArray(v[0]);
}

function f(x: string[] | string[][]): string[][] {
  return isMatrix(x) ? x : [x];
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.