Home > OS >  TypeScript: Ability to infer/derive values for type from const object literal, nested with non-uniqu
TypeScript: Ability to infer/derive values for type from const object literal, nested with non-uniqu

Time:10-06

I have a style guide object that I would like to be able to use TS/IDE to see specific literal values from, instead of inferred type. For example:

const guide = {
  colors: {
    black: {
      medium: "#000000",
    },
    blue: {
      medium: "#3884F7",
      dark: "#053986",
    }
...
  },
  typography: {
    font: {
      family: "Commissioner",
      size: {
        xxs: "11px",
        xs: "12px",
        s: "14px"
...
    },
  },
};

Is there a way to have (for example) guide.colors.blue.dark typed as "#053986" rather than string without remapping the entire object to a type object (or objects) manually.

CodePudding user response:

You can use a const assertion to tell the compiler to infer the most specific type it can from an object initializer, including the literal types of its property and subproperty values:

const guide = {
  colors: {
    black: {
      medium: "#000000",
    },
    blue: {
      medium: "#3884F7",
      dark: "#053986",
    }

  },
  typography: {
    font: {
      family: "Commissioner",
      size: {
        xxs: "11px",
        xs: "12px",
        s: "14px"

      },
    },
  }
} as const; // <-- const assertion

which produces

/* const guide: {
    readonly colors: {
        readonly black: {
            readonly medium: "#000000";
        };
        readonly blue: {
            readonly medium: "#3884F7";
            readonly dark: "#053986";
        };
    };
    readonly typography: {
        readonly font: {
            readonly family: "Commissioner";
            readonly size: {
                readonly xxs: "11px";
                readonly xs: "12px";
                readonly s: "14px";
            };
        };
    };
} */

Playground link to code

  • Related