Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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:
https://stackoverflow.com/a/22886730/6103920
https://stackoverflow.com/a/29759472/6103920