Skip to content

Type inference issue with spread and generics #37934

Closed

Description

We notice the following issue described in this playground.

TL;DR;

The type inferred when merging two objects trough a generic function is always resolved to T & U which is inexact if T shares keys with U.

The correct inferred type of const mergeObjects = <A, B>(a: A, b: B) => ({ ...a, ...b });

should be

type Merge<T, U> = { 
    [k in Exclude<keyof T, keyof U>]: T[k];
} & {
    [l in Exclude<keyof U, keyof T>]: U[l];
} & {
    [l in keyof (T | U)]: T[l] | U[l] 
};
<A, B>(a: A, b: B) => Merge<A, B>

As shown in the playground, the correct type is inferred when using the spread operator with concrete types.

Activity

  1. RyanCavanaugh commented on Apr 14, 2020

    @RyanCavanaugh
    Member

    The proposed definition is much more complex yet still not fully accurate because it can't account for aliasing effects.

    See discussion in #28234

  2. typescript-bot commented on Apr 16, 2020

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  3. flovilmart commented on Apr 18, 2020

    @flovilmart
    Author

    Thanks for pointing it out.

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions