The error message "Duplicate identifier readonly" occurs in TypeScript when there are multiple declarations of a property named Constants.read

I have implemented the following code in utils -> Constants.ts for my Angular project.

Constants.ts

 export class Constants {
     static readonly LOCAL_STORAGE  = 'LOCAL_STORAGE';
     static readonly SESSION_STORAGE  = 'SESSION_STORAGE';
  }

An error occurs: Duplicate identifier readonly. (property) Constants.readonly : string. when hovering over readonly.

Additionally, [ts] '=' expected. [ts] Cannot find name LOCAL_STORAGE any. is the message displayed when hovering over LOCAL_STORAGE.

When attempting to retrieve data from session_storage in another ts file using let mobileNo = this.db.get(Constants.SESSION_STORAGE, Constants.MOBILE_NO);, the following error is encountered:

property 'SESSION_STORAGE' does not exist on type 'typeOf Constants' any.

If anyone could assist me with this issue, it would be greatly appreciated.

Answer №1

It appears that the readonly properties feature was first introduced in version 2.0 of typescript. Make sure to verify that your current typescript version is equal to or greater than 2.0.

I had no issues utilizing your class within a fresh stackblitz project. https://stackblitz.com/edit/stackoverflow-54596178

Answer №2

It appears that you are attempting to establish a string enum. In TypeScript 2.4, the introduction of string enums allows your code to function seamlessly:

enum E {
    hello = "hello",
    world = "world"
};

For older versions of TypeScript:

export const Enum = createStringEnum(["Prop1", "Prop2"]);
export type Enum = keyof typeof Enum;

function createStringEnum<T extends string>(keys: T[]): {[K in T]: K} {
    return keys.reduce((res, key) => {
        res[key] = key;
        return res;
    }, Object.create(null));
}

The createStringEnum function generates an object with matching keys and values as strings provided in the array.

Moreover, keyof typeof Enum; equates to "Prop1" | "Prop2".

By utilizing Enum, you can ensure the type's accuracy and extract the string values present within the object.

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

Retrieve items from the <ng-content></ng-content> within the corresponding component in the TypeScript file

I'm facing an issue where I can't retrieve elements from ng-content within the same component. Here is my setup: Component HTML <div> <ng-content #action></ng-content> <app-comp2></app-comp2> </div> Component ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

Data string not being converted correctly to date format

Here is a table I am currently working with: ID DateColumn 1 3/7/2019 5:29:38 AM 2 3/8/2019 5:28:38 AM 3 3/7/2019 5:30:38 AM 4 3/7/2019 5:31:38 AM The date column in this table is being processed as a string when bound to the grid. To ...

How to import a child component in Angular 2 [v2.4.10] without declaring it in the

I am facing a dilemma with two components parent.component.ts @Component({ selector: 'my-element', template: ` <h4>{{title}}</h4> <child-element></child-element> //<-- I need to retrieve data from ...

Executing initial function in Angular 2 before the first routing takes place

I'm working on an app that needs to load all messages from the server before fully launching. Currently, I have placed the HTTP request in my app component's OnInit method. However, I am facing an issue where the routing does not wait for the d ...

Unable to retrieve the headers from the error response

When working with Angular 6, I encountered an issue where I couldn't retrieve the headers from an HTTP error response. Specifically, when the server responded with a status code of 401, additional headers were included in the error response. What is t ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Utilize Charts.js to transform negative values into graphical representations

I am struggling with transforming the expense data into a positive number in my bar chart. The data consists of both income and expenses, and I want to display them as positive numbers for easier comparison. I attempted using Math.abs(this.barData[1]) in n ...

typescript with React's Context API

Have you seen my demo? This is a basic React application built with Typescript. I'm experimenting with React's Context API. One of the key components I've set up is the ThemeContext, which contains simple theme styling values for use in o ...

Tips for building numerous leaflet maps within an Angular page

My leaflet open street map is designed as shown below. .component.ts map = L.map('map').setView([12.876, 80.599], 12); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href=& ...

Using Angular to enhance a Bootstrap NavBar with a Dropdown feature

I've been attempting to implement the default NavBar from Bootstrap documentation directly as shown in the examples. However, it seems to be not functioning properly. The UI displays correctly but the dropdown feature is not working. Please refer to ...

Is there a memory leak causing Node.js memory growth in the (system)?

I have come across a peculiar memory leak in our live environment, where the heap continues to grow due to (system) objects. Heap snapshot Here is a memory dump showing a spike in memory usage up to 800MB: https://i.sstatic.net/vvEpA.png It seems that t ...

Error: TypeScript cannot find @types declaration for restify-client

Currently, I am attempting to upgrade to the most recent version of restify (6.4.2). Our application is written in TypeScript. The clients have now been separated into their own package starting from the previous version of restify we were using (4.3.2) - ...

What is preventing the return type of document.createElement from being designated to a specific generic that is limited to HTMLElement?

Currently, I am in the process of developing a function called clone(el). This function needs to accept an HTMLElement or any subtype of it and return the same type that is provided. Can someone assist me in correctly structuring the generic signature for ...

Issue encountered while attempting to start a project using Ionic

After cloning a repository using the git clone command and running npm install, I encountered a message with warnings about vulnerabilities: npm WARN deprecated" and at the end it says "55 vulnerabilities (3 low, 12 moderate, 36 high, 4 critical) To addres ...

Tips for fixing prettier errors in express and TypeScript code

I have set up a simple Node/Express + Typescript application app.listen(PORT, (): void => { console.log(`app is running in ${environment} and listening on port ${PORT}!`); }); I am encountering an error and I am unsure of the cause? Replace PORT, wit ...

What is the best way to implement rest parameters in Typescript when making a function call?

I have been working on NestJS and I am facing an issue with retrieving data from the database based on the name property that I pass in a service method. When I pass {"name": "item1"} in Postman, I get data related to item1. However, when I pass {"name":"i ...

Using React to display an HTTP response containing text or HTML content

I am currently developing an application that allows users to upload an .xls file to a server, and in return, they receive a text/html response. I am looking for a way to preview this response in a similar manner to what is seen in developer tools. Here is ...

Displaying an observable array in Angular 8 using console.log

Having an issue displaying the response from an observable on the console in my Angular project. It seems to be coming back as undefined when retrieved from a service. Even when attempting to loop through the data, I get an error stating that it is not ite ...

Angular does not support the dropdown functionality of bootstrap-select

Here are the instructions to be executed in the index.html of your Angular project: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angular12</title> <base href="/& ...