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