javascripttypescript

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:

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.