I have JSON array as below:
var json = [{
id: 1,
login: "Mieszko",
name: "Misztal",
surname: "Adminek",
phone: "0413414",
role: 2
},
{
id: 2,
login: "Rafal",
name: "Robak",
surname: "Kierowczek",
phone: "5145145",
role: 1
}
];
I have also created User class as below:
export class User extends BaseModel {
id: number;
login: string;
name: string;
surname: string;
phone: string;
roles: Roles;
admin: boolean;
driver: boolean;
isDriver(): boolean {
return this.roles === 1;
}
//other methods
}
My plan is to cast incomming JSON array to User array. Inside JSON I get role as integer. I have admin and driver boolean fields in my class. This is needed in ngModel for checkboxes.
Now the problem is after this line
var users: Array<User> = JSON.parse(JSON.stringify(json));
I cannot call method from User class e.g users[0].isDriver()
because compiler doesn't recognize isDriver() method.
Does anyone know how to solve this?
TypeScript type assertions
TypeScript allows you to override its inferred and analyzed view of types any way you want to. This is done by a mechanism called "type assertion".
Type assertions have two forms. One is the "angle-bracket" syntax:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
And the other is the as-syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Answer to this question
In your case the problem is not the type assertion though. You are trying to assigning an array of plain JSON objects to users variable and then trying to call a method that doesn't exist on an object (users[0].isDriver is undefined).
You can't simply cast a plain object to a JavaScript/TypeScript class instance. You have to instantiate a User first. There are a number of techniques for doing it, and generally involve copying data.
For an example solution of "casting" a JSON to an instance of TS class please see one of the following answers:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With