[Typescript] Create a Union From an Object's Values

Let's say we have a const of object:

export const programModeEnumMap = {
  GROUP: "group",
  ANNOUNCEMENT: "announcement",
  ONE_ON_ONE: "1on1",
  SELF_DIRECTED: "selfDirected",
  PLANNED_ONE_ON_ONE: "planned1on1",
  PLANNED_SELF_DIRECTED: "plannedSelfDirected",
} as const;

 

We want to get Individual program values: 

"1on1"|"selfDirected"|"planned1on1"|"plannedSelfDirected"
 
import { Equal, Expect } from "../helpers/type-utils";

export const programModeEnumMap = {
  GROUP: "group",
  ANNOUNCEMENT: "announcement",
  ONE_ON_ONE: "1on1",
  SELF_DIRECTED: "selfDirected",
  PLANNED_ONE_ON_ONE: "planned1on1",
  PLANNED_SELF_DIRECTED: "plannedSelfDirected",
} as const;

type IndividualKeys = Exclude<keyof typeof programModeEnumMap, "GROUP" | "ANNOUNCEMENT">;

export type IndividualProgram = typeof programModeEnumMap[IndividualKeys];

type tests = [
  Expect<
    Equal<
      IndividualProgram,
      "1on1" | "selfDirected" | "planned1on1" | "plannedSelfDirected"
    >
  >
];

 

posted @ 2022-12-11 20:35  Zhentiw  阅读(14)  评论(0编辑  收藏  举报