[Typescript] Tips: Derive a union type from an object

const fruitCounts = {
  apple: 12,
  banana: 23
}

type PropUnion<T extends Record<PropertyKey, any>> = {
  [K in keyof T]: {
    [K2 in K]: T[K2]
  }
}[keyof T]

type FruitCounts = PropUnion<typeof fruitCounts>

posted @ 2022-09-26 13:53  Zhentiw  阅读(21)  评论(0编辑  收藏  举报