Instructions on declaring a Typescript variable that will only be assigned once in the future

In the land of coding, there are two constants: const which sets a value at declaration, and let which allows for variables to be changed. But what about a special Typescript (or javascript) variable that starts as undefined, and once defined, remains forever unchangeable?

Answer №1

Implementing this logic in JavaScript can be a bit tricky when using a single primitive value. However, you can ensure type safety by incorporating setter and getter methods. The setter method checks if the value has already been set, while the getter method retrieves it.

const customObject = (() => {
  let value: number;
  return {
    setValue: (newValue: number) => {
      if (value !== undefined) {
        throw new Error('Value has already been set');
      }
      value = newValue;
    },
    getValue: () => {
      if (value === undefined) {
        throw new Error('Value has not been set yet');
      }
      return value;
    }
  };
})();

// will throw an error
const result1 = customObject.getValue();

// will return 3
customObject.setValue(3);
const result2 = customObject.getValue();

// will throw an error if run just after the above
customObject.setValue(5);

Answer №2

It appears that in this case, const cannot be used and only let is allowed. Additionally, you must specify the initial type to prevent it from inferring to any by default. Alternatively, you can use a union type like string| number so that you can later assign it to either of those types.

let value: string;      // string | number
value = 'newValue as string' 

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

Determining the instance type of a TypeScript singleton class

I have a unique singleton implementation: class UniqueSingleton { private static instance: UniqueSingleton; private constructor() { // Only allows instantiation within the class } public static getInstance(): UniqueSingleton { if (!Unique ...

Can someone provide instructions on how to convert base64 data to an image file

I'm utilizing the vue-signature Library but I am unsure how to download the base64 data that is generated as an image. Here is the link to the library: https://www.npmjs.com/package/vue-signature. I have gone through the documentation and noticed that ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

Each loop iteration results in the array being randomly ordered

My goal is to store multiple objects in an array and then render them out in a specific order. This is my process: app.js var allOdds = []; var count = 0; // ===================================== /* Database Configuration and Error Handling */ // ====== ...

What is the method for including a class in the anchor element that is the closest sibling of the containing ul element in the HTML structure?

I'm currently exploring traversal in jQuery and I'm a bit confused about how the class is being added to all the items in the unordered list. I know it's probably something simple that I'm missing. Any assistance would be greatly apprec ...

Tips for creating a hover-activated dropdown menu

How can I create a drop-down menu in my horizontal navigation bar that appears when hovering over the Columns tab? The drop-down menu should include options such as Articles, Videos, Interview, and Fashion. To better illustrate what I am looking for, here ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...

Finding all elements with a specified attribute in jQuery: A comprehensive guide

While looking for an example, I came across one that searches only inputs instead of all elements: https://api.jquery.com/attribute-equals-selector/ Is there a way to modify this example so that it can search all elements in the DOM, and not just inputs ...

Enhance user experience by implementing an interactive feature that displays

I have a form for adding recipes, where there is an ingredients button. Each recipe can have multiple ingredients. When the button is clicked, an input field for adding ingredients should appear below the ingredient button. What I've attempted so far ...

Monitor changes in the visible price range in lightweight-chart

Is there a way to detect when the visible price range changes in lightweight-chart, similar to how the timeScale's visible time range change can be detected through subscribeVisibleTimeRangeChange? I couldn't find anything related in the document ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

What is the best way to access the current webdriver instance using code?

Currently, I am in the process of creating an end-to-end test suite with Protractor. As Protractor is based on WebdriverJS, I am attempting to utilize some of its functionality. More specifically, my goal is to incorporate certain behaviors using Webdriv ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Issue with Backbone: Browser button failing to activate routes

Recently, I have been working on a web application using backbone, jQuery, and the BAAS of stackmob. However, I've encountered an issue where browser buttons do not trigger the backbone routes as expected. Despite successfully navigating from one view ...

What is the best way to detect an empty string in AngularJS?

When working with a form, I needed to ensure that a string is not empty. If the string is indeed empty, I wanted to set a default value. Otherwise, I wanted to pass the actual value. Below is the code snippet from the controller: $scope.addElem = functi ...

The Angular2 promise resolves before the web service call has finished executing

I have a service in Angular 2 that contains a function responsible for providing data for a dropdown list. This particular function returns a promise. Below is the code snippet from the service: getStuff(): Promise<Stuff> { return t ...

Is it possible for a React application to manage errors (status code 4xx) using a try-catch block

Currently delving into React (using hooks) and facing an interesting challenge. I am in the process of building a Notes Application (from FullStackOpen's learn react section). The database I'm working with only allows notes with content length gr ...

Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive th ...

Tips for effectively matching a type definition pattern in TypeScript

Good evening! I'm currently working with Angular and rxjs, but I have a feeling that TypeScript is going to play a significant role in my project today. I've been exploring different methods to achieve my goal, but it's definitely challengi ...

JQuery Ajax call fails to retrieve any information

I have been experimenting with JQuery Ajax methods. I created a basic Ajax request to retrieve specific 'tagged' photos from Flickr. Here is the code snippet I am using: function initiateSearch() { $(function() { var tagValue ...