Skip to content

Type guard cannot remove undefined from Partial<T>[keyof T] | undefined #45257

Open
@Jason3S

Description

@Jason3S

Bug Report

When writing a function to merge object A with non-undefined values from object B into C where A is of type T and B is of type Partial<T>, I came across a situation where the type guard seems to be failing.

🔎 Search Terms

  • type guard
  • Partial

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about common-bugs-that-arent-bugs

⏯ Playground Link

Playground link with relevant code

💻 Code

function merge<T>(a: T, b: Partial<T>, keys: (keyof T)[]): T {
    const v: T = { ...a };
    for (const key of keys) {
        const value = b[key];
        if (value !== undefined) {
            v[key] = value;
        }
    }
    return v;
}

🙁 Actual behavior

There is an error at v[key] = value;:

Type 'T[keyof T] | undefined' is not assignable to type 'T[keyof T]'.
  Type 'undefined' is not assignable to type 'T[keyof T]'.

image

Clearly value is NOT undefined, yet the compiler complains that it is.

🙂 Expected behavior

I would expect that the code compiled.

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions