4

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?

miechooy
  • 3,178
  • 12
  • 34
  • 59
  • 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 '17 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 '21 at 09:14

1 Answers1

9

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:

  1. https://stackoverflow.com/a/22886730/6103920
  2. https://stackoverflow.com/a/29759472/6103920
Community
  • 1
  • 1
Jakub Synowiec
  • 5,719
  • 1
  • 29
  • 37