Can a constant value be dynamically defined in Typescript?

Trying to dynamically define a constant in Typescript has proven to be more challenging than I anticipated.

Here's what I attempted:

  define(name: string, value: any): boolean {
    var undef;
    const name = value;
    return name == undef;
  }

The method is supposed to be called like this:

define ('MY_CONST_NAME', 'foo_value);

However, I encountered the following error:

Duplicate 'name' identifier.

This error didn't come as a surprise to me, but I'm stuck on how to work around it and achieve my objective.

Answer №1

Simply put, the answer is no. Const in JavaScript is block scoped, meaning it is only available within the block in which it is declared. If you're looking to make something immutable, it's not difficult to achieve. However, this question suggests a possible lack of knowledge on the topic. A more useful approach may be learning how to deep freeze an object, preventing any additions, deletions, or changes. Keep in mind that deep freezing can present challenges if you need to make changes further down the object structure.

Refer to MDN for more information:

var obj = {
  prop: function() {},
  foo: 'bar'
};

// Making changes to frozen objects will fail
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;

var o = Object.freeze(obj);

o === obj; // true
Object.isFrozen(obj); // true

obj.foo = 'quux'; // no effect
obj.quaxxor = 'the friendly duck';

function fail(){
  'use strict';
  obj.foo = 'sparky'; // throws TypeError
  delete obj.quaxxor; // throws TypeError
  obj.sparky = 'arf'; // throws TypeError
}

fail();

Object.defineProperty(obj, 'ohai', { value: 17 }); // throws TypeError
Object.defineProperty(obj, 'foo', { value: 'eit' }); // throws TypeError

Object.setPrototypeOf(obj, { x: 20 }) // throws TypeError
obj.__proto__ = { x: 20 } // throws TypeError

Answer №2

Although the question was unclear, a solution can still be found by utilizing types:

type Custom = Record<string, string>

const myCustomVars: Custom = {}

myCustomVars.text = "hello"

console.log(myCustomVars.text)

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

The page abruptly jumps to the top whenever I display an ID element

Im currently facing an issue with my webpage where everything seems to be functioning properly, except for one problem. When I set a hidden element to be shown, the page suddenly jolts upwards. Although the previously concealed element is successfully disp ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Imitate a style using jQuery without deleting other elements

This is an example of HTML code: <div id="id1" style="width:100px;background: rgb(196, 14, 14);">1</div> <div id="id2" style="margin-top:10px">2</div> to <div id="id1" style=&qu ...

Sending arguments to child components within KnockoutPassing parameters to child components in

My coding setup includes the following template: <template id="item-list"> <form action="" data-bind="submit: addItem"> <input type="text" name="addItem" data-bind="value: newItem"> <button type="submit">Add Item</butt ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

What is the best way to display an international phone number using Angular Material V6?

I've been working on a project that utilizes Angular Material V6. My goal is to display international phone numbers with flags in a Material component text box. After some research online, I came across an npm module that achieved this but it was tail ...

When modifying a string in React, the edit always somehow ends up at the very tail end

In my ReactJS app, I have a Material-UI input element. Everything is working well except for one issue - when I try to edit the text in the middle of the string, the cursor always jumps to the end of the string after every letter I input. I suspect this m ...

What is the process for transferring an image from a cloud function request to the vision API?

Just set up a Google Cloud Function with an HTTP endpoint. I want to pass an image to this endpoint and have it sent all the way to the Vision API (which is already set up) and then receive the response back. So, in essence: image in POST request -> C ...

Automatically forward to m.example.com on mobile devices using nodejs

Is there a way to create a subdomain in Node.js, such as m.example.com, and have it redirect to m.example.com on mobile devices? I've searched for answers but haven't found a satisfactory solution. One suggestion is to use nginx in front of Node, ...

Utilizing Vue.js with Firestore: Retrieve information from Firestore without rendering any data on the screen

When attempting to display my data from Firestore, I encountered an issue where the data was retrieved successfully when hovering over the <td> tag but not actually displayed. Here is my file for fetching data from Firestore: <template> & ...

Tips for Navigating and Scrolling to an Element by its ID in a Next.js Page Enhanced with AnimatePresence

Currently, I am utilizing Framer Motion to add animations to the page transitions in a Next.js project. However, when implementing AnimatePresence, it seems to interfere with the navigation to specific elements using hash links (id). The seamless transitio ...

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

Despite calling this.setState to update my state, the render() method is still displaying the previous values

class EditLocation extends Component { constructor(props) { super(); this.state = { LocationId: '', locationOptions: [], } this.baseState = this.state; this.findLocationById = this ...

Using target="_blank" does not seem to open a popup window in React

The issue is that the target="_blank" attribute is not working properly for the modal popup window. Instead, the link is opening in the same page and the popup is closing. <TermLink to="/legal/privacy-policy" target="_blank"> Privacy Pol ...

The Strapi registration feature in version 4 is giving a "method not allowed 405" error, which

Feeling a bit confused with a Strapi query. I am currently working on v4 and trying to set up a registration feature. The code snippet for invoking the function is provided below. Everything seems fine, such as submitting function variables, etc. However, ...

Having various ng-apps within a single parent app

Exploring angularjs for the first time and experimenting with multiple ng-apps on a single page. For example, having app2 inside app1 and app1 within rootApp. controller1 includes an $http service that retrieves id and name values and assigns them to $roo ...

The scroll functionality does not seem to be functioning as intended on mobile devices when

Hey there, I'm currently working on making my navbar sticky and applying it when the page is scrolled. The code I have works flawlessly on desktop, but unfortunately, it doesn't seem to work on the mobile version. Any suggestions? window.addE ...

What is the best way to form a new type that encompasses all shared properties found within a union of types?

Is there a method to safely map over the union of arrays without hard-coding specific types? When attempting to calculate newArr1, an error is encountered: Property 'field2' does not exist on type 'Common<A, B>'. How can this err ...

Solution: Resolve clientY scrolling issue within an HTML document

I am facing an issue with the positioning of my context menu. When I right-click and scroll down, the menu does not maintain its regular position. Instead of appearing to the right of the mouse cursor when stationary, it moves below the cursor based on how ...