Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference issue with spread and generics #37934

Closed
flovilmart opened this issue Apr 13, 2020 · 3 comments
Closed

Type inference issue with spread and generics #37934

flovilmart opened this issue Apr 13, 2020 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@flovilmart
Copy link

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.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 14, 2020
@RyanCavanaugh
Copy link
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

@typescript-bot
Copy link
Collaborator

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

@flovilmart
Copy link
Author

Thanks for pointing it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants