0

I have an object that looks like this

const codeMap: Record<string, number> = {
  level1: 1,
  level2: 2,
  level3: 3,
  level4: 4,
};

How can I create a type like the one below without having to list every value in the codeMap?

type codeMapValues = 1 | 2 | 3 | 4

1 Answer 1

0

If you annotate codeMap as Record<string, number> you are widening its type to the point where the compiler has no idea which particular property keys or values exist, other than to know that each value will be of type number. If you want the compiler to remember the exact mapping, you should drop the annotation and use a const assertion to let it know that you actually expect codeMap's values to stay put and not be changed via assignment, like codeMap.level2 = 123 or something:

const codeMap = {
  level1: 1,
  level2: 2,
  level3: 3,
  level4: 4,
} as const;

Once you do that, you can use typeof codeMap to query the type of the codeMap value and then look up its property values:

type CodeMapValues = typeof codeMap[keyof typeof codeMap];
// type CodeMapValues = 1 | 2 | 3 | 4

Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.