相关文章推荐
豪气的眼镜  ·  从JDK 8升级到JDK ...·  7 月前    · 
帅气的高山  ·  44. ...·  8 月前    · 
爱吹牛的稀饭  ·  Java8 Stream之groupingB ...·  1 年前    · 
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?

How is that array a JSON array??? It's either an array, or data in the JSON format. That looks an awful lot like an array to me, irrespective of what you call the variable that holds it... – bug-a-lot Jan 31, 2017 at 10:32 This is not a duplicate. Again editors rush to gain new SO badge instead of giving the propert consiseration to a question. There is no answer to the question in the link proposed as being unique question. – Valentine Shi Aug 25, 2021 at 9:14

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
  •