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-objectentries #304

Open
utterances-bot opened this issue Nov 20, 2022 · 6 comments
Open

type-challenges-solutions/en/medium-objectentries #304

utterances-bot opened this issue Nov 20, 2022 · 6 comments

Comments

@utterances-bot
Copy link

ObjectEntries

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-objectentries.html

Copy link

zhaoyao91 commented Nov 20, 2022

This doesn't work for such cases

Expect<Equal<ObjectEntries<{ key: 1 | undefined }>, ['key', 1 | undefined]>>,
Expect<Equal<ObjectEntries<{ key?: 1 | undefined }>, ['key', 1 | undefined]>>,

@ghaiklor
Copy link
Owner

@zhaoyao91 did you manage to improve the solution to get those tests passing?

@zhaoyao91
Copy link

@ghaiklor sadlly, I didn't find a perfect solution yet. Naive solution would indeed pass most cases but the Partial<Model> one. see type-challenges/type-challenges#19507

Copy link

This is my solution so far

type ObjectEntries<
  T extends Record<keyof any, any>,
  K extends keyof T = keyof T
> = K extends any
  ? [K, Required<T>[K] extends never ? undefined : Required<T>[K]]
  : never;

Copy link

Here is my solution: all test cases passed:

type ObjectEntries<M, T = Required<M>> = {
      [P in keyof T]-?: [P, T[P] extends never ?  undefined : T[P]]
  }[keyof T]

Copy link

Update:
no need -?:

type ObjectEntries<M, T = Required<M>> = {
      [P in keyof T]: [P, T[P] extends never ?  undefined : T[P]]
  }[keyof T]

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