The practice of following the UpperCamelCase convention post object transformation

I encountered a situation where I have an object that returned the result from an RxJs subscribe method:

result: any
{
    message: null
    role: Object
    success: true
}

To better manage this object in TypeScript, I decided to convert it to a type called MyResponse:

export class BaseResponse {

        public Message: string = null;

        public Success: boolean = null;

    }

export class MyResponse extends BaseResponse {

        public Role: Role = new Role();

    }
..
getModel() {
    this.roleService.get(this.id).subscribe(
        result => {
            let getResponse: MyResponse = <MyResponse>result;
            console.log(getResponse.Role.ApplicationId); // <-- null reference error
        },
        error => { },
        () => {
        }
    );
}  

An issue I noticed is that when inspecting the getResponse object in Chrome debugger, its properties' names start with lowercase letters instead of uppercase. Is there a way to modify them to be capitalized?

getResponse
{
    role: Object, 
    message: null, 
    success: true
}

Answer №1

When using the <> operator in TypeScript, it is important to note that it is not a type cast but rather a type assertion. This means that TypeScript only influences the type checking at compile time and not during runtime.

For example:

let getResponse: MyResponse = <MyResponse>result;

This code does not actually change the value of the response. Instead, it simply instructs the compiler to infer the MyResponse type. Therefore, if the server response has properties in uppercase, they will remain in uppercase at runtime unless you apply a transformation function to change them to lowercase.

More information on type assertion can be found here: https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html


EDIT: Additional Explanation

Even if you define MyResponse as a class, TypeScript treats it as an interface when declaring getResponse. As a result, the line public Role: Role = new Role(); is not executed as expected. To initialize this property, you would need to create a new instance with new MyResponse().

Should object properties be uppercase? Can I make them uppercase?

In JavaScript development, object properties are typically lowercase. However, if you are accustomed to uppercased properties from languages like C#, you have the flexibility to choose either option based on your preference.

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

MUI Gradient Tracked Button

Take a look at this Codepen example I created. It showcases a hover effect where the gradient follows the mouse cursor. In order to achieve this effect, I have defined two CSS variables - --x and --y, to keep track of the mouse position on the button. The ...

Incorporating Paypal subscription functionality and refining subscription challenges

The angular project I'm working on requires configuring a PayPal payment gateway for create subscription, cancel subscription, and upgrade subscription functionalities. I have encountered two issues with PayPal: 1) The PayPal button has been success ...

Sending HTTP POST request with FormData from an Angular2 client to a Node server

I am having trouble sending a file from my Angular2 client to my NodeJS server using http and a FormData object. upload.html ... <input #fileinput type="file" [attr.multiple]="multiple ? true : null" (change)="uploadFile()" > ... upload.component. ...

Tips for incorporating Material UI Icon v1.0.0-beta.36 into a .tsx component

Currently utilizing material-ui-icons v1.0.0-beta.36. I am endeavoring to incorporate a Search icon within a .tsx component. .tsx component: import React, { Component, ReactElement } from 'react' import Search from 'material-ui-icons/Sear ...

Event callback type narrowing based on the specific event key

While exploring different approaches to create a type-safe event emitter, I came across a pattern where you start by defining your event names and their corresponding types in an interface, as shown below: interface UserEvents { nameChanged: string; ...

Embracing Typescript promises over jQuery deferred for improved code efficiency and reliability

Currently, I have the following lines of code that utilize the JQueryDeferred object from the type definition class jquery.d.ts. My goal is to replace jQuery deferred with TypeScript promises. Here is the existing JQueryDeferred code: class A { privat ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

What is the best way to set State conditionally based on two different objects, each with its own type, without resorting to

I am trying to create two different objects, each with slightly different types, in order for them to be compatible with a state object that contains values of both types. However, I am encountering the following error: Property 'dataA' does no ...

Angular 2 vertical carousel: Spinning in a new direction

Does anyone know of an awesome plugin for creating a vertical carousel in Angular 2 that includes animations? I attempted to use ng-angular carousel, and although I was able to make it vertical, I ran into issues when trying to have each slide with differ ...

Transferring information between two pages when a button is clicked in Angular

How can I display hero details on the hero-details page when clicking a button? I'm currently struggling to make it work. When I click the button, the details show up on the hero-list page, but using the routerLink doesn't display the data. I am ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

Step-by-step guide to minify Typescript files with Webpack

I am facing an issue in my webpack configuration while trying to minify the output bundle when working with TypeScript. Currently, only one file has been migrated to TypeScript in my project and it works fine with babel-node and the dev bundle without Ugli ...

Utilizing identical child components in Angular 2 parent component

My goal is to have a page with 2 tabs, each containing a table. To simplify the structure of the tables, I decided to create a custom component for a table and use it as a child component. Here is how I structured my parent page: <p-tabPanel> ...

What function is missing from the equation?

I am encountering an issue with an object of type "user" that is supposed to have a function called "getPermission()". While running my Angular 7 application, I am getting the error message "TypeError: this.user.getPermission is not a function". Here is w ...

When utilizing ng-content alongside *ngtemplateOutlet, the content does not appear visible within the DOM

I'm working with three Angular components - a base component and two child components (child1 and child2). The structures are as follows: child1.component.html <ng-template #child1Template> <div> <h1>CHILD 1</h1> ...

Having trouble initialising an array of objects in TypeScript? (TS1109: Expression expected)

While working on my project, I encountered a problem when trying to create an array of objects: Error TS1110: Type expected Error TS1109: Expression expected https://i.sstatic.net/Y5qb8.png This is how my array is structured: export let COUNTRIES: A ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

Tips for incorporating state properties into a component

Currently engrossed in a project revolving around state management for individual components utilizing Angular 7 and NGRX. The challenge at hand is to ensure scalability of the implementation, allowing multiple uses while maintaining independence. Thus fa ...

transferring data between components in a software system

I received a response from the server and now I want to pass this response to another component for display. I attempted one method but ended up with undefined results. You can check out how I tried here: how to pass one component service response to other ...