Skip to content

Mapping generic types breaks inference/narrowing #16267

Closed
@jaredru

Description

@jaredru

TypeScript Version: 2.3.4

Code

interface I {
    x: number | null;
}

function generic<T extends I>(a: T, b: Partial<T>) {
    if (a.x != null) {
        a.x.toFixed(2); // OK
    }

    if (b.x != null) {
        b.x.toFixed(2); // ERROR: Property 'toFixed' does not exist on type 'T["x"]'
    }
}

function notGeneric(a: I, b: Partial<I>) {
    if (a.x != null) {
        a.x.toFixed(2); // OK
    }

    if (b.x != null) {
        b.x.toFixed(2); // OK
    }
}

Expected behavior:

The mapped generic code should compile without error.

Actual behavior:

The mapped generic code does not compile.

For context, the place I'm seeing this issue is React when interacting with props. The React typings for a Component are:

class Component<P, S> {
    props: Readonly<{ children?: ReactNode }> & Readonly<P>;
    // snip
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions