What is causing the compilation error in the following code snippet, and how can it be resolved:
function f(x: string[] | string[][]): string[][] {
return Array.isArray(x[0]) ? x : [x];
}
Upon inspection, it appears that the return value will constantly be of type string[][]
. This is because if x
is of type string[]
, then x[0]
will not be an array, and if x
is of type string[][]
, then x[0]
will be an array.
Despite this, TypeScript is unable to infer the correct type and throws an error.
Is there a way to resolve this issue without type casting? If so, how?