Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: how to get possible keys from const with limited values?

I have the following code:

export const mapLayers: Record<string, SomeObject> = {
  layer_a: {},
  layer_b: {}
} as const;

export type LayerId = keyof typeof mapLayers;

LayerId will always be string and not layer_a | layer_b which I would expect.
It actually does work if I remove the Record<string, SomeObject> part. But then I lose the possiblity to limit what’s in mapLayers values. How can I get proper inferred keys AND also the "limited" values?

TS Playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Sounds like a case for the satisifes operator:

export const mapLayers = {
  layer_a: {},
  layer_b: {}
} satisfies Record<string, SomeObject>;

This tells typescript that it should infer the type strictly (similar to as const, without making properties readonly). In addition though, it tells typescript you want an error to happen if the result is incompatible with Record<string, SomeObject>

For more on satisfies, see this documentation page

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading