1

I have a config object that I'm using the keys of as a type. Like so:

type Trait = "fast" | "blue" | "smug";

const ThingsObject = {
  car: ["fast"],
  sky: ["blue"],
  bluebird: ["fast", "blue"],
  sonic: ["fast", "blue", "smug"],
} as const;

type Thing = keyof typeof ThingsObject;

The issue I'm running into is I can't seem to find a way to typecheck that ThingsObject should -- in addition to being a const object -- also be Record<string, Trait[]>

Here are things that don't work:

// Putting the type constraint anywhere in assignment makes the keys just string
const ThingsObject: Record<string, Trait[]> = { ... } as const
type Thing = keyof typeof ThingsObject; 
// ISSUE: typeof Thing === string
// Trying to make something else error
const TestAssignment: Record<string, Trait[]> = ThingsObject;
// ISSUE: assignment not allowed.  Can't assign an `{} const` to anything.  

How can one simultaneously make use of the benefits of const and the benefits of type checking?

So far, the best I've found is to just switch back and forth between assignment types every once in a while.


Based off the duplicate question and jcalz answer, here's the solution

Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • See the answer to the linked question. If I use the `satisfies` function from there it yields [this code](https://tsplay.dev/w24Y9m). – jcalz Mar 03 '22 at 02:10
  • For my purposes, this does work (ts playground link added). One does have to remove the const constraint, which means not all benefits of const are present. But the benefit that mattered for this question remains. Thank you. – Seph Reed Mar 03 '22 at 17:58

0 Answers0