In Typescript, define a class with a property that will serve as the name of another type's property

Trying to define a class property for another type:

class TypeOne {
    public static readonly code: string = 'code';
}

class TypeTwo { public [TypeOne.code]: TypeOne }

Encountering an error message:

The computed property name in the class property declaration must have a simple literal type or a unique symbol

Successfully using constants from an enum:

enum TypeThree {
    key = 'key'
}

class TypeFour { public [TypeThree.key]: TypeThree }

Any suggestions on setting a constant value as an immutable key for the compiler to recognize the field name?

Answer №1

To remove the string annotation, you can do the following:

class TypeOne {
    public static readonly key = 'key';
}

class TypeTwo { public [TypeOne.key]: TypeOne }

In TypeScript, it is necessary to use a literal type for the property name instead of a general string.

Answer №2

To set TypeOne you can define it this way:

class TypeOne {
    public static readonly key = 'key'; // Eliminate the string note
}

This specifies the value of key as a constant, with the literal string 'key', making it unique and avoiding complaints from the compiler.

Playground

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 Javascript function is designed to function exclusively with onclick events or setTimeout functions

I am currently working on a website that I want to be responsive to the window size. However, I am facing an issue with vertical alignment. I have created a jQuery function to handle this, and it works well for divs with images but not so well for a div wi ...

Steps for integrating .web extension files in React Native Web using Typescript

When using react native web, there is a potential to utilize files with extensions such as .web and .android. For example: myFile.web.js myFile.android.js These files can then be included like so: import myFile from './myFile'; React Native w ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Guide to retrieving variables stored in Local Storage using javascript and jquery while building an HTML form

In my HTML form, I have three select tags that create drop-down menus for the user. The total is calculated at the bottom of the form when a value is selected. Upon clicking 'save', the data is stored in local storage with four keys and their res ...

How to customize the color of Navbar pills in Bootstrap 4 to fill the entire height

Is there a way to ensure that the background of nav-items is completely filled with color rather than just partially? I attempted to use Bootstrap pills, but it did not achieve the desired effect. I also experimented with my own CSS, but encountered simil ...

Is it possible to include multiple URLs in a single cURL request to retrieve product information?

I am trying to retrieve products from the "generic/products" URL and the "generic/all_products" URL using a single cURL request. Here is my code: <?php $ch = curl_init(); $request_url = "HTTP://www.yourdomain.com/net/WebService.aspx?"; $request_u ...

Setting the paths property in a project with multiple tsconfig.json files: a step-by-step guide

My file structure is organized as follows: |__ app1/ | |__ tsconfig.json |__ utilities/ | |__ files.ts |__ base-tsconfig.json I have defined the paths property in base-tsconfig.json like this: "compilerOptions": { "baseUrl": ".", "pa ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

Issue with Angular Swiper carousel: Error message pointing to node_modules/swiper/angular/angular/src/swiper-events.d.ts

I am attempting to implement a carousel in Angular using Swiper (). An error message is appearing: Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not meet the constraint ...

Configuring TypeScript to utilize worker_threads

Currently, I am attempting to implement WebWorkers in my Typescript project and I have encountered a hurdle. Despite having installed @types/node and updating everything, 'worker_threads' has transitioned from an experimental feature to a stable ...

Include TypeScript in a single component within an already established Vue project

I've been working on a large Vue project and I want to integrate TypeScript into it. However, every time I try to do so, I run into a lot of errors that take weeks to fix. Instead of going through that, I'd like to find a way to add TypeScript to ...

Issue with passing props from parent component to child component in Vue.js not functioning

As a newcomer, I have been assigned a project that involves using Vuejs. In this project, there is a page that utilizes a component called DashboardCard. Each DashboardCard receives 2 props - val and icon from the parent component. https://i.stack.imgur. ...

component is receiving an incompatible argument in its props

I am facing a situation where I have a component that works with a list of items, each with an ID, and a filtering function. The generic type for the items includes an ID property that all items share. Specific types of items may have additional properti ...

Translate array into object with correct data types (type-specific method)

Welcome In our project, we have implemented attributes support where each attribute acts as a class. These attributes include information on type, optionality, and name. Instead of creating an interface for every entity, my goal is to automate this proces ...

submission of form data and automatic redirection to another page

Seeking advice on managing form submissions and page redirection. I have a landing page with a basic form, where users select criteria and are then redirected to page2 displaying tabular data and query information. When submitting the form on Page1, data ...

Prevent displaying JSON output following response.send in NodeJS

In my Node.js application, I have a response.send function: this.app.post('/profile', (req, res) => { let password = req.body.password; let newWallet = operator.createWalletFromPassw ...

Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column. var name = ['Akansha', 'Navya']; var age ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

Can Javascript be used to obtain someone's UDID?

Is it feasible to retrieve individuals' UDIDs when they visit your website? If this is achievable, could you recommend a helpful tutorial for me to follow? ...

How can async/await help in retrieving the value of a CORS request?

Trying to make a CORS request and utilize async/await to extract the value from it (using jquery). The functions createCORSRequest and executeCORSRequest seem to be functioning correctly, so the implementation details are not my main concern. The function ...