The problem is this line:
let o = <pers>JSON.parse(s);
I belive you think this is a type-cast, but it is not. This is a type-assertion, which does not imply runtime support. Basically, you are only telling the compiler to believe o
is of type pers
, but that is not true at runtime:
o instanceof pers; // false
You will either need to manually create the object instance using your JSON as Nitzan suggests, or create a routine that reads some metadata information to automatically create the correct instances with the corresponding properties.
For the latter approach, I would recommend trying out TypedJSON, which I created to provide an elegant and widely adaptable solution to this exact problem:
@JsonObject
class pers {
@JsonMember name = "";
@JsonMember last = "";
constructor(name?: string, last?: string) {
this.name = name;
this.last = last;
}
alo() {
alert(this.name);
}
}
let o = TypedJSON.parse(s, pers);
o instanceof pers; // true
o.alo(); // "ben"
Note the parameterless constructor, that is required (in most similar systems, as well).
This solution builds on ReflectDecorators, but it's not required (however, without it you will need to manually specify the constructor function of properties: @JsonMember({ type: String }) ...
for example).