ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
470 stars 56 forks source link

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

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

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

zhaoyao91 commented 1 year ago

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 commented 1 year ago

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

zhaoyao91 commented 1 year ago

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

albert-luta commented 1 year ago

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;
JanessaTech commented 1 week ago

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]
JanessaTech commented 1 week ago

Update: no need -?:

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