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's as const v JavaScript's Map object

I have a simple object:

const simpleObject = {
  one: 'one',
  two: 'two',
  three: 'three'
}

Now, I understand that pre ES2015 objects could not be guaranteed to return keys in the same order that they were inserted. But this is not such a problem these days.

We are using TypeScript and the question of the effect of whether as const would in fact maintain key order came up:

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

const simpleObject = {
  one: 'one',
  two: 'two',
  three: 'three'
} as const

It is unclear what effect as const would have.

JavaScript’s Map object does maintain key order and so could be used instead of the object above.

So what can be used and what is best to be used when we want key order to be preserved?

>Solution :

as const has no effect in runtime. It instructs the (typescript) compiler to infer the narrowest type for that specific expression.

You can see that in the typescript playground for simplicity, by looking at the transpiled code

If the order of the keys matters, use a Map, since as mentioned above as const does not have any effect in runtime whatsoever.

To answer to the question It is unclear what effect as const would have, the answer is that for the developer experience it will give you a narrower type, but it won’t have any effect in runtime.

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