The immutability of TypeScript's `as const` compared to JavaScript's Map object

Let's delve into a straightforward example:

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

Historically, pre ES2015 objects did not guarantee the preservation of key order upon retrieval. However, this is less of an issue in modern times.

Within our TypeScript implementation, we questioned whether using as const would actually maintain the original key order:

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

The impact of applying as const remains ambiguous.

Notably, JavaScript's Map object upholds key order, presenting a viable alternative to the above object.

When prioritizing the preservation of key order, what options are available and which solution proves most effective?

Answer №1

Using as const in TypeScript does not impact runtime behavior. Instead, it tells the compiler to determine the most specific type for that particular expression.

This can be easily observed in the TypeScript playground by examining the transpiled code here

If the order of keys is important, consider using a Map as mentioned in the Mozilla Developer Network documentation here. The use of as const has no bearing on runtime functionality.

In response to the question about the impact of as const, it is mainly beneficial for enhancing developer experience by providing a more precise type inference without any effect on runtime behavior.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieving information from rechart's hover/tooltip feature

I'm currently attempting to access the data object created by recharts that is used to populate tooltips. My goal is to display this data elsewhere. The screenshot below displays the result of console.log(data.payload[0]); This data is accessed thro ...

Using Angular-Translate to Replace Variables in Title Tags

In my AngularJS project, I am using Angular-Translate version 2.6.1. One of the challenges I am facing is how to include a variable in a translated title attribute within a span element. <span title={{'translationID'|translate:'{username ...

Implementing access restrictions for modules in NodeJS

In Node, is it possible to limit access or permit access only to specific modules from a particular module? Should I consider replacing the require function and object in the global scope for this purpose? I have concerns about the security of a certain mo ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

Navigating through the directories in PUG using the absolute path

Referring to the docs for PUG (), it states: If a path is absolute (example: include /root.pug), it gets resolved by prepending options.basedir. Otherwise, paths are resolved in relation to the file being compiled. To clarify, I understand that this in ...

Draggable element with a centered margin of 0 auto

Encountering an issue with jQuery UI sortable/draggable where the element being dragged, when centered using margin:0 auto, starts dragging from the left side of the container instead of the center where it is positioned. Check out this demo to see the pr ...

Retrieve an Array Containing a Mix of Objects and Functions in Typescript

Let's address the issue at hand: I spent several months working with a custom React Hook using plain JavaScript, and here is the code: import { useState } from 'react'; const useForm = (initialValues) => { const [state, setState] = ...

Retrieve a multitude of nested Records within the returnType that correlate with the number of arguments provided to the function

My goal is to dynamically define a deeply nested ReturnType for a function based on the number of arguments passed in the "rest" parameter. For example, if we have: getFormattedDates( dates: Date[], ...rest: string[] // ['AAA', 'BBB&apos ...

JS - Activate the ghost element feature by using the preventDefault function

I am currently working on a project where I need to drag elements from a list of img tags to various svg:rect containers. The process involves using mousedown and mouseup events to track which img is being picked from the list and where it is dropped with ...

Is there a way to use CSS to generate a disappearing triangle-shaped div that will only vanish when clicked directly on the triangle and not when clicked on the surrounding overflow area?

In a different discussion, it was mentioned that the method used to create a CSS triangle allows for triggering the hover state or click event only when the cursor is inside the triangle. There is a demo provided to demonstrate this with the hover state. ...

pass extra parameters to breeze-saving-server functions

Currently, I am working on a project using Durandal. In order to retrieve and save data, I am using Breeze. However, I am facing an issue where I need to send additional parameters to the server when saving, such as the user who is saving the entity. The s ...

Facing issues with the template URL not functioning properly during the migration from Angular 1.5 to Angular 6

I am currently in the process of migrating an Angular 1.5 project to Angular 6, but I've encountered an issue with the templateUrl not working in the Angular 1.5 component. The packages I am using are: Angular CLI 6.0.8 TypeScript 2.7.2 Angular 6.0.7 ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

"Troubleshooting Angular: Uncovering the Root of the Issue with

I have set a specific pattern for the email field which should follow this format: pattern="^(([^<>()\[\]\.,;:\s@\']+(\.[^<>()\[\]\.,;:\s@\']+)*)|(\'.+\'))@(( ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Utilizing local storage functionality within AngularJS

I've been encountering challenges while trying to integrate local storage using ngStorage in my ongoing AngularJS project. Despite fixing what seems to be the root cause of data type problems and errors during debugging, issues persist. Here is the P ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

Replicating a Bootstrap element without transferring all event listeners

Recently, I posted a query on Stack Overflow regarding the cloning of a bootstrap element while excluding the copied event listener. The solution provided was to refrain from passing true to the clone() function. Upon further reflection, I've realize ...

AngularJS - A Guide to Determining the Time Span Between Two Dates

I am trying to figure out the exact number of months and days between two specific dates. For example, if the start date is "Jan 12, 2014" and the end date is "Mar 27, 2017", the result should be "38 months and 15 days". However, I am currently only able ...