10

In the source code of ts-toolbelt, there is often an intersection of an empty object and a mapped type. For what purpose is this done?

export type ReadonlyFlat<O> = {
  +readonly [K in keyof O]: O[K];
} & {}; // there

export type OptionalFlat<O> = {
  [K in keyof O]?: O[K];
} & {}; // there

type __Pick<O extends object, K extends keyof O> = {
  [P in K]: O[P];
} & {}; // there
gekkedev
  • 562
  • 4
  • 18
Alexander Pankin
  • 475
  • 2
  • 10
  • 4
    https://github.com/millsp/ts-toolbelt/commit/1b1ac71c337619b5a7e75cf8dca2612fdc0e41ff is the commit that did this, whose message is "fix(deep): over-computation on deep types & recursive mapped types". Not sure if there's any more information about that. – jcalz Oct 01 '21 at 18:43
  • 3
    Also from that commit: "_add `& {}` for better computation we can only do this if the mapped type is not intended to go deep (recurse) because `& {}` forces computation, if we do it deeply => resolves to `any` this happens only when a type is nested within itself => infinite recursion_" – JDB Oct 01 '21 at 18:45
  • 1
    Note that I'm not really sure how to turn this into an answer; it's specific to a particular library and without some [mre] of the problem it claims to prevent it's hard to know what to say that isn't just opinion or conjecture. – jcalz Oct 01 '21 at 19:26

0 Answers0