Retrieve the name of a property or field from an object with a specified type

I have an angular class that is injectable with a readonly property. I do not have control over the initialization of this class as it is meant to be used in a library. Consumers of this library can access these properties but are not allowed to modify them.

@Injectable()
export class MyState {
   readonly requestToken: string;
}

The trick used by the library to write to the property is causing issues.

self.state[<any>"requestToken"] = requestToken;

The problem arises when the name of the property changes and the TypeScript compilation does not detect the string assignment.

Is there a way to obtain the name of the property in a typed manner? Something like:

var nameOfRequestTokenProperty = somethingXxx MyState => requestToken;

Answer №1

The compiler won't reveal the name of a property to you, but you can ensure that any changes to the name will trigger an error using keyof:

const authTokenKey: keyof MyState = "authToken"; // Any change in the keyname will generate an error
self.state[<any>authTokenKey] = authToken;

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

What made the "in" operator not the best choice in this situation?

When I set out to create a type that represents the values of a given object type, I initially came up with this: type Book = { name:string, year:number, author:string } // expected result "string" | "number" type ValueOf<T ex ...

Can the return type of a function be determined dynamically at runtime by analyzing a function parameter value?

Let's delve into this concept with an illustrative example! interface Query { foo: any; } interface Mutation { bar: any; } type OperationName = keyof Query | keyof Mutation; const request = async <T>(args, operationName: OperationName): P ...

I encountered some problems with conflicting Angular dependencies, so I decided to delete the node_modules folder

An error has occurred: The module 'H:\All_Files\Scripts\Angular\example\node_modules\source-map\source-map.js' could not be found. Please ensure that the package.json file contains a correct "main" entry. ...

Referring to TypeScript modules

Consider this TypeScript code snippet: module animals { export class Animal { } } module display.animals { export class DisplayAnimal extends animals.Animal { } } The objective here is to create a subclass called DisplayAnimal in the dis ...

How to extract a string value from an observable array in Angular2 NativeScript?

I inserted JSON data into an observable array. My goal is to extract only the address from ShowData, specifically as a string value based on its position. ShowData.ts: class ShowData{ constructor(public id:number, public name:string, public address:s ...

How to replace/redirect the import statement in TypeScript from { X } to 'Y'

My situation involves an external library known as Y, which was installed using npm and loaded from the node_modules directory. This library is hosted on GitHub and currently being utilized in my project in the following manner: import { X } from 'Y& ...

Tips on preventing Realtime database onWrite trigger function callback from iterating through data that has been altered

I am currently developing a 1 vs 1 game matching system using a real-time database. The system works by creating a record in the users table when a user signs in. Once there are two players with a status of placeholder, a cloud function generates a gameInf ...

The bar chart functions perfectly on localhost but encounters issues after being hosted on Gitpage

Localhost Gitpage The bar chart was displaying correctly on localhost, but once it was hosted on Gitpage, it began to show issues. Any suggestions on how to resolve this? Repository Link: https://github.com/mzs21/bar-chart Live Preview: ...

Utilizing imported symbols across multiple script blocks in a Vue Single File Component

I am currently working with a Vue Single File Component that has two <script> blocks: one for setup and another for Vue Router's beforeRouteEnter handler, which cannot be used in setup. Both blocks may require some of the same imports. Interesti ...

What is the best way to transform HTML into a PDF using Angular 2?

Is there a way to convert a dynamically generated HTML table into a PDF and also have the ability to print it using Angular 2 and Typescript? ...

Regular expression for the validation of emails using a delimiter

Can someone help me create a regex expression for emails? This is what I have so far: \S+@\S+\.\S+ I want to repeat this X times with a ; separator. Any ideas on how to achieve this? For example, the pattern should allow strings like: ...

Grid Layout with truncation in two dimensions

In my development using Material UI v5 for layouting, I've encountered an issue with truncating a string within a 2-dimensional Grid layout, specifically within a Dialog box. I am trying to create a file upload component with the desired layout shown ...

Tips for patiently anticipating an object to undergo asynchronous modifications?

I have an array containing items, and I need to incorporate the asynchronous value from getProductMinQuantity. The issue I'm facing is that the response with res.status(200)... gets sent before modifying item.order_quantity_minimum. I had assumed us ...

Is it possible to loop through a subset of a collection using *ngFor?

Is it possible to iterate through a specific range of elements in a collection using *ngFor? For instance, I have a group of checkboxes with their form control name and label specified as follows: [{id: 'c1', label: 'C1'}, ...] Assum ...

Exploring the elements within the ContentChildren directive in Angular

Presenting my component: import { Component, OnInit, ContentChildren, QueryList } from '@angular/core'; import { IconBoxComponent } from '../icon-box/icon-box.component'; @Component({ selector: 'app-three-icon-box', temp ...

Ensure that the JSON file containing translations is fully loaded prior to proceeding with the loading of the Angular application

In our Angular application, we have integrated internationalization using ng2-translate. We are utilizing the .instant(...) method for translations to simplify the process without having to subscribe to observables. One issue we are facing is that using . ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

Nest may struggle with resolving dependencies at times, but rest assured they are indeed present

I've encountered a strange issue. Nest is flagging a missing dependency in a service, but only when that service is Injected by multiple other services. cleaning.module.ts @Module({ imports: [ //Just a few repos ], providers: [ ServicesService, ...

Errors related to Typescript are causing issues with the stock installation of Next.js

Whenever I use typescript with create-next-app, my tsx files are filled with numerous "Problems" messages. These errors only appear in Visual Studio Code and do not affect the build process. I have tried uninstalling vscode, removing all extensions, and ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...