Skip to content

Control flow analysis inference of a generic mapped type #27945

@JasonKleban

Description

@JasonKleban

When upgrading to 3.1.3 I get a new error not in 3.0.3:

I see two problems in the type checking of the sample below.

  1. before const lo: number = min!;, the return after null test of either identifier means that both will be non-null.
  2. Even so, I'm asserting non-null and still it thinks it could be null. The subsequent acceptance of lo2 which includes null as an option suggests that it isn't a problem with the T["min"] and number half.

(There is no error without the generic aspect of this sample.)

interface RangeSelectorStateBase {
    min: number | null;
    max: number | null;
}

type RangeSelectorState<T> = {
    [P in keyof (T & RangeSelectorStateBase)]: (T & RangeSelectorStateBase)[P];
}

function foo<T>(state : RangeSelectorState<T>) {
    const { min, max } = state;

    if (min === null || max === null) {
        return;
    }

    const lo: number = min!; // Type 'T["min"] & null' is not assignable to type 'number'.
    const hi: number = max!; // Type 'T["min"] & null' is not assignable to type 'number'.

    const lo2: number | null = min; // type-checks fine.
    const hi2: number | null = max; // type-checks fine.
}

playground link

Full error text:

Type 'NonNullable<(T & RangeSelectorStateBase)["min"]>' is not assignable to type 'number'.
  Type '(T["min"] & null) | (T["min"] & number)' is not assignable to type 'number'.
    Type 'T["min"] & null' is not assignable to type 'number'.
      Type 'NonNullable<T["min"] & null> | NonNullable<T["min"] & number>' is not assignable to type 'number'.
        Type 'NonNullable<T["min"] & null>' is not assignable to type 'number'.
          Type 'T["min"] & null' is not assignable to type 'number'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions