Skip to content

Bad inference for param of type T[] | T[][] #3370

@jsnajdr

Description

@jsnajdr

Steps to reproduce

Try to compile this code:

function isNestedArray<T>(arr: T[] | T[][]): arr is T[][] {
	return Array.isArray(arr) && Array.isArray(arr[0]);
}

type TG = { a: string };

function convert(controls: TG[] | TG[][]): TG[][] {
  if (isNestedArray(controls)) {
    return controls;
  } else {
    return [ controls ];
  }
}

(for example, in the tsgo.sxzz.dev playground)

Behavior with typescript@6.0

In 6.0 the code compiles cleanly, and the T parameter of isNestedArray is correctly inferred as TG.

Behavior with tsgo

With tsgo there is an error:

main.ts(8,21): error TS2345: Argument of type 'TG[][] | TG[]' is not assignable to parameter of type 'TG[][][] | TG[][]'.
  Type 'TG[]' is not assignable to type 'TG[][][] | TG[][]'.
    Type 'TG[]' is not assignable to type 'TG[][][]'.
      Type 'TG' is missing the following properties from type 'TG[][]': length, pop, push, concat, and 35 more.
main.ts(9,5): error TS2322: Type '(TG[][] | TG[]) & TG[][][]' is not assignable to type 'TG[][]'.
  Type 'TG[] & TG[][][]' is not assignable to type 'TG[][]'.
    The types returned by 'pop()' are incompatible between these types.
      Type 'TG | undefined' is not assignable to type 'TG[] | undefined'.
        Type 'TG' is missing the following properties from type 'TG[]': length, pop, push, concat, and 35 more.
main.ts(11,14): error TS2322: Type 'TG[][] | TG[]' is not assignable to type 'TG[]'.
  Type 'TG[][]' is not assignable to type 'TG[]'.
    Property 'a' is missing in type 'TG[]' but required in type 'TG'.

Apparently the inference is "one array level off", where T is inferred as TG[] instead of TG.

A necessary condition to reproduce is that TG is a "complex" type like { a: string }. With a primitive type like string the bug doesn't happen.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions