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-challenges-solutions/en/medium-merge #251

Open
utterances-bot opened this issue Oct 4, 2022 · 5 comments
Open

type-challenges-solutions/en/medium-merge #251

utterances-bot opened this issue Oct 4, 2022 · 5 comments

Comments

@utterances-bot
Copy link

Merge

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-merge.html

Copy link

zavarka commented Oct 4, 2022

A version that is a few characters shorter - keyof F | keyof S is the same as keyof F & S. But I could be missing something. :)

type Merge<F, S> = {
  [P in keyof (F & S)]: P extends keyof S
    ? S[P]
    : P extends keyof F
    ? F[P]
    : never;
};

@ghaiklor
Copy link
Owner

ghaiklor commented Oct 5, 2022

@zavarka clever 😺 I think there could be some edge-cases with properties in a sense how they will be treated when intersecting them, but for common cases should work, yes.

Copy link

dgh500 commented Oct 16, 2022

Using a util function admittedly ( also from the 'Append to Object' challenge ) but the Collapse ( or Flatten ) just satisfies the tests - without it the solution is equivalent.

type Merge<F, S> = Collapse<S & {
  [K in keyof F as K extends keyof S ? never : K]: F[K]
}>

type Collapse<T extends { [k: string]: any }> = {
  [K in keyof T]: T[K]
}

Copy link

Why should we use k extends key F again because k is in keyof F | keyof S

type Merge<F, S> = {
  [P in keyof F | keyof S]: P extends keyof S
    ? S[P]
    : F[P]
};

@ghaiklor
Copy link
Owner

@BruceYuj yes, because your key can be either in first set or another one, and you need to filter out one of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants