Currently I'm working on a typescript project and I'm really enjoying the type inference that TypeScript brings to the table. However - when getting objects from HTTP calls - I can cast them to the desired type, get code completion and call functions on them compile time, but those result in errors runtime
Example:
class Person{
name: string;
public giveName() {
return this.name;
}
constructor(json: any) {
this.name = json.name;
}
}
var somejson = { 'name' : 'John' }; // Typically from AJAX call
var john = <Person>(somejson); // The cast
console.log(john.name); // 'John'
console.log(john.giveName()); // 'undefined is not a function'
Although this compiles nicely - and intellisense suggests me to use the function, it gives a runtime exception. A solution for this could be:
var somejson = { 'name' : 'Ann' };
var ann = new Person(somejson);
console.log(ann.name); // 'Ann'
console.log(ann.giveName()); // 'Ann'
But that will require me to create constructors for all my types. In paticular, when dealing with tree-like types and/or with collections coming in from the AJAX-call, one would have to loop through all the items and new-up an instance for each.
So my question: is there a more elegant way to do this? That is, cast to a type and have the prototypical functions available for it immediately?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…