Skip to content

Type inference issue with spread and generics #37934

Closed
@flovilmart

Description

@flovilmart

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.

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