Skip to content

Generics narrowing not considering constraints when conditional is involvedΒ #51523

@Tiedye

Description

@Tiedye

Bug Report Feature Request?

πŸ”Ž Search Terms

generics conditional types narrowing

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Generics, Type System Behavior

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface State {
    a: string;
    b: { value: string};
    c: { value: string};
}
type NestedKey = "b" | "c";

type A<T> = T;

function f<T extends keyof State>(key: T, v: A<State[T]>) {
}

type B<T> = T extends object ? T : never;

function g<T extends keyof State>(key: T, v: B<State[T]>) {
}

// this works

function ex1<T extends NestedKey>(key: T) {
    f(key, {value: ''});
}

// this doesn't

function ex2<T extends NestedKey>(key: T) {
    g(key, {value: ''}); // this should not throw an error but it does
}

πŸ™ Actual behavior

It seems when a conditional type is used, the compiler isn't evaluating the constraint of the given type parameter and instead falling back to the constraint defined locally.

πŸ™‚ Expected behavior

The arguments type should be narrowed using the most constrained generic regardless of conditional types

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions