Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface properties are changed to Pascal Case from camel Case

I am using Angular 1.4 with type script, and RXJS in an ASP.NET 5 application. I am having extremly wiered issue. During the runtime, all my interface properties are being turned to Pascal Casing from camel casing. Why is this happeing and how to avoid this ?

Please note i am using promises to get data from web api making call 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);
}

Here is how i have defined the interface

export interface IResponse{

     firstName : string;
     lastName : string;
     age : number


}

When i get the the data back, its properties are having CamelCasing like this making them in accessible.

response.data.FirstName
response.data.LastName
response.data.Age
like image 783
ATHER Avatar asked Oct 25 '25 06:10

ATHER


2 Answers

Most probably the server uses PascalCasing, and you defined an interface which does not match the data returned by a server. TypeScript will not convert member names from PascalCase to camelCase, you have to write your own logic. It will not throw an error at runtime either, because interfaces get erased. I suggest you to break the naming convention in the TypeScript part, use PascalCase fields, so the interfaces will match the data transfer objects exactly. So define the interface like this:

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

And access the field names like data.FirstName

Another way to go is to change the server implementation, as Cleverguy25 suggests.

like image 139
Tamas Hegedus Avatar answered Oct 26 '25 21:10

Tamas Hegedus


If your backend is WebApi, by default the normal Json serialization leaves the fields as they are in you c# or vb.net casing.

Look at this article to configure the formatter to return camel casing.

http://richarddingwall.name/2012/03/10/returning-camelcase-json-from-asp-net-web-api/

like image 41
Cleverguy25 Avatar answered Oct 26 '25 21:10

Cleverguy25