I have the following object with values returned as result a from RxJs subscribe method:
result: any
{
message: null
role: Object
success: true
}
And I convert it to MyResponse
type in TypeScript:
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 => { },
() => {
}
);
}
The problem is that looking at getResponse
object in Chrome debugger, the objects' properties' first letters are lowercase. Shouldn't it be uppercase? Can I make it uppercase?
getResponse
{
role: Object,
message: null,
success: true
}
The <>
operator is not a type cast, because TypeScript "is not present" at runtime any more. Only at compile time. It is type assertion.
So
let getResponse: MyResponse = <MyResponse>result;
does not change the value. It will only tell the compiler that it should infer the MyResponse
type. So if the response from the server has uppercased properties, they still will be uppercased at runtime. If you want them to be lowercased you need to apply a transform function.
You can read more about type assertion here: https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html
EDIT: You updated your question, I'll add some more info below.
Even though you defined MyResponse
as a class
, TypeScript will not use it as such in your code (when setting getResponse
). TypeScript will use the class as an interface. Thus, public Role: Role = new Role();
is not executed. If you want to initialize this property you have to create a new instance, e.g. new MyResponse()
.
Shouldn't it be uppercase? Can I make it uppercase?
In JavaScript land object properties are usually lowercased. But working with some C# backend I got used to have uppercased properties, too ;) So it's your decision.