How to derive a type based on an object keys?

  Kiến thức lập trình

I need to derive a type ColorVariant from PALETTE object. The expcected result is:

type ColorVariant = "common.black" | "common.white" | "primary.25" | "primary.50" | "primary.100" | "error.25" | "error.50" | "error.100" | "success.25" | "success.50" | "success.100"

Actual result is:

type ColorVariant = never

Code:

const PALETTE = {
  common: {
    black: "#000",
    white: "#fff",
  },
  primary: {
    25: "#FAFAFF",
    50: "#F5F5FF",
    100: "#E7E7FC",
  },
  error: {
    25: "#FFFBFA",
    50: "#FEF3F2",
    100: "#FEE4E2",
  },
  success: {
    25: "#F6FEF9",
    50: "#ECFDF3",
    100: "#D1FADF",
  },
} as const;

export type Colors = keyof typeof PALETTE;
export type ColorOptions = (typeof PALETTE)[Colors];
export type Tone = keyof ColorOptions;

export type ColorVariant = `${Colors}.${Tone}`;

I do understand that this happens because of different keys in common and primary, error, success…unfortunately I do not undetstand how can I fix it. Please help

Here’s TS playground

LEAVE A COMMENT