Skip to content

Incorrect widening (constraint fallback?) during inference when union with undefined appears in constraintΒ #44891

@Mesteery

Description

@Mesteery

Bug Report

πŸ”Ž Search Terms

union, type inference, imprecise union generic type, generic type.

πŸ•— Version & Regression Information

This is reproducible on all versions of the playground.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

export interface Something<
  R extends
    | {
        [K in 'foo' | 'bar' | 'baz']?: {
          r?: unknown;
          p?: unknown;
        };
      }
    | undefined = undefined
> {}

const o: Something<{ foo: { r: 1; p: 2 }; bar: { r: 3 } }> = {};

declare function something<M extends T extends Something<infer R> ? keyof R : never, T extends Something>(
  key: M,
  something: T
): M;

declare function somethingBugged<M extends T extends Something<infer R> ? keyof R : never, T extends Something>(
  key: M,
  something: T
): [M];

const normal = something('foo', o);
// got: "foo"
// expected: "foo"

const bugged = somethingBugged('foo', o);
// got: ["foo" | "bar"]
// expected: ["foo"]

// However with `as const`, the correct type is returned.
const ugly = somethingBugged('foo' as const, o);
// got: ["foo"]
// expected: ["foo"]

πŸ™ Actual behavior

The type loses its precision and is the union instead of the exact type.

πŸ™‚ Expected behavior

The type is exact.


What is strange is that the generic type M loses precision ("foo" -> "foo" | "bar") with the somethingBugged function which returns a tuple of M (and it does the same thing with any other "wrapper", such as an object).
Whereas with the something function there is no problem. Both functions are identical.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: check: Type InferenceRelated to type inference performed during signature resolution or `infer` type resolution

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions