In Typescript, interfaces are required to have properties written in Pascal Case instead of camel Case

Currently, I am facing a strange issue in my ASP.NET 5 application where I am using Angular 1.4 with TypeScript and RXJS. Somehow, during the runtime, all my interface properties are getting converted from camel casing to Pascal casing. This unexpected behavior is causing difficulties for me. Can anyone explain why this is happening and suggest how to prevent it?

It's worth mentioning that I am utilizing promises to fetch data from a web API, following a pattern like this:

public GetDataFromAPI(request: Messages.IRequest): Observable<Messages.IResponse> {
    let result: IPromise<Messages.IResponse>;
    result = this.$http.post("http://api.domain.com/GetData", request).then(
        (response: ng.IHttpPromiseCallbackArg<Messages.IResponse>) => {
            return response.data;
        }
    ); 
 return Observable.fromPromise(result).retry(3);
}

Below is an example of how I have declared the interface:

export interface IResponse{
     firstName : string;
     lastName : string;
     age : number
}

Upon receiving the data back, I noticed that its properties are now in Pascal casing instead of CamelCasing, which makes them inaccessible through their original names.

response.data.FirstName
response.data.LastName
response.data.Age

Answer №1

It is likely that the server utilizes PascalCasing and you have defined an interface that does not align with the data structure returned by the server. TypeScript does not automatically convert member names from PascalCase to camelCase, so it would be necessary for you to implement your own logic for this conversion. Additionally, errors will not be thrown at runtime because interfaces are eliminated during compilation. A recommended approach would be to diverge from the naming convention in the TypeScript section and use PascalCase fields in order to perfectly match the data transfer objects. Therefore, define the interface as follows:

export interface IResponse {
    FirstName : string;
    LastName : string;
    Age : number;
}

You can access the field names like data.FirstName

An alternative solution would be to adjust the server implementation, as proposed by Cleverguy25.

Answer №3

This is the setup that must be adjusted:

HttpConfiguration settings = new HttpConfiguration();
var jsonHandler = settings.Formatters.Where<JsonMediaTypeFormatter>().First();
jsonHandler.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonHandler.SerializerSettings.Formatting = Formatting.Indented;

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 data type 'StaticImageData' cannot be converted to type 'string'

I've hit a roadblock with interfaces while working on my NextJS and TypeScript project. I thought I had everything figured out, but I'm encountering an issue with the src prop in my Header component. The error messages I keep receiving are: Typ ...

Issues with AngularJS <a> tag hyperlinks not functioning as expected

After performing a search, I have an array of objects that needs to be displayed on the template using ng-repeat. The issue arises when constructing the URL for each item in the array – although the ng-href and href attributes are correct, clicking on th ...

Combining rxjs events with Nestjs Saga CQRS

I am currently utilizing cqrs with nestjs Within my setup, I have a saga that essentially consists of rxjs implementations @Saga() updateEvent = (events$: Observable<any>): Observable<ICommand> => { return events$.pipe( ofType(Upd ...

Injection of dependencies in Angular can be done outside of the constructor

In my class, I have a constructor that takes in some data. export class MyClass { constructor(data: any) { this.data = data; } } I also want to include ChangeDetectorRef as a parameter in the constructor like this. constructor(data: any, cd: ...

Is it true that a TypeScript derived class is not allowed to have identical variable names?

Why is it not allowed for TypeScript derived classes to have the same variable name, even if these members are private? Is there another way to achieve this, or am I making a mistake? class ClassTS { private nom: string = "ClassTS"; ...

The reason for duplicating the import of an NPM package in TypeScript (specifically for Firebase Functions)

I recently found this code snippet in the Firebase documentation: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; import 'firebase-functions'; admin.initializeApp(); I'm curious ...

Protractor's elementExplorer is malfunctioning, and the REPL is not showing up on Windows

Having some difficulty getting elementExplorer to work. Here's what I've been trying: node node_modules\protractor\bin\protractor .\protractor.dev.conf.js --baseUrl http://angularjs.org --elementExplorer Using the following ...

What's the significance of & in TypeScript and JavaScript?

While exploring someone else's code, I came across this interesting piece related to the props of a React component. Although I'm aware that & is typically used as an AND logical operator, it seems to have a different significance in this con ...

What is the best way to share a page on social media platforms like Facebook or Twitter based on the current route in AngularJS

I am facing an issue with sharing a page in AngularJS. When I click on the "Facebook Share button," it only takes the Open Graph data of the home page, rather than the data of the specific page that I am trying to share. Any assistance would be greatly ap ...

Verify whether $modal is currently open like $dialog.isOpen

Currently in the process of upgrading from AngularJS 1.1.15 to 1.3.15, facing an issue with transitioning from $dialog to $modal. If anyone has any useful resources or tips for this migration, it would be greatly appreciated! I am currently handling it on ...

Creating an Array in AngularJS with ng-model and submitting it with jQuery: A comprehensive guide

I am struggling to submit an array of values using jQuery and AngularJS. Whenever I click the submit button, only the first array value is being retrieved. How can I get all array values using ng-model? Here is a link to all my code: https://jsfiddle.net/r ...

Updating the value of the variable using ng-submit

My application displays Quantity: {{num}}. The default value is set to 3 in the scope. The objective is to click on: <form ng-submit="addContact()"> <input class="btn-primary" type="submit" value="Add Contact"> </form> and to up ...

Explanation on How to utilize the $( document ).ready() jQuery function within the ngAfterViewInit() on a Component class using Angular 2

This is the code snippet: constructor(private el: ElementRef) { } ngAfterViewInit() { this.loadScript('app/homepage/template-scripts.js'); } ...

issue with custom cors policy implementation

I have a unique custom CORS policy implementation shown below, in which I explicitly set support-credentials to false: public class CorsProviderFactory : ICorsPolicyProviderFactory { //https://msdn.microsoft.com/en-us/magazine/dn532203.aspx publi ...

In Angular 2, property binding will not function properly when attempting to bind to an object

I have encountered a strange issue with Angular 2 property binding. Let's start with the Store class: export class Store { id: number; name: string; address: string; } This is the component code snippet: export class MyBuggyComponent i ...

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...

Challenges encountered when attempting to round significant amounts with ng-currency

In my current project, I am utilizing the ng-currency library to handle currency values. While it serves its purpose, there are some specific requirements that need to be addressed: The currency value should not be negative. It should not exceed 999,999, ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

Angular 6 combined with Firebase is experiencing difficulties with routing after a successful login

After spending hours trying to fix my issue, I still can't figure it out. I've searched through related threads on SO, but haven't found a solution yet. Issue After successfully signing up, the email verification flag is set to true. Howev ...

The attribute 'disabled' is originally defined as a characteristic within the class 'CanColor & CanDisableRipple & HasTabIndex & MatChipBase'. However, it is replaced in the current context of 'MatChip' as an attribute

After updating my Angular version from 9.1 to 11, I encountered a compilation error. Error: node_modules/@angular/material/chips/chips.d.ts:120:9 - error TS2611:'disabled' is defined as a property in class 'CanColor & CanDisableRipple &a ...