Dalorzo
Dalorzo

Reputation: 20014

Casting from JSON in Typescript not working

Given the following classes

class A {
   constructor(){
      this.name ="Some name";
    }
  name:string;
}

class C extends A {
  
  get Age() {
    return 21;
  }

  SayHello(){
      return "Hello";
  }
  
}

If you would to build the OBJECT from a JSON Parse

var demo2:C= JSON.parse('{"name":"Joan of Arc"}') AS C;

This will not work:

console.log(demo2.Age);
console.log(demo2.SayHello());

Any workaround or ideas?

Upvotes: 1

Views: 281

Answers (2)

Chaz Ashley
Chaz Ashley

Reputation: 409

It doesn't work because Typescript doesn't cast JS objects, meaning that it doesn't change or modify them, it's only used for types. So when you use as statement, demo2 is being treated by Typescript as instance of C, while in reality demo2 isn't instance of C. To make it work you can modify C so it has a constructor which accepts an object and assigns its properties to this

// add this to the body of C
constructor(obj: C) {
 Object.assign(this, obj);
}
// later in code
const demo2 = new C(JSON.parse('{"name":"Joan of Arc"}') AS C);

Upvotes: 1

Daniel Farina
Daniel Farina

Reputation: 173

JSON.parse(...) as AnyClass will not (cast) or create the object AnyClass.

One clever solution are:

const parsedJson = JSON.parse(...)
const myObj = new AnyClass();
Object.assign(myObj, parsedJson);

Upvotes: 1

Related Questions