小编Mar*_*usT的帖子

从Typescript解析JSON会恢复数据成员但不会返回类型:无法调用结果上的方法

当我将对象p1的JSON字符串化结果解析回另一个对象p2时,第二个对象获取与第一个对象关联的数据,但我无法在其上调用任何nethods.使用http://www.typescriptlang.org/Playground/我尝试了以下内容:

class Person
{
    constructor(public name: string, public age: number) {
    }
    Age() { return this.age; }
}

// Create a person
var p: Person = new Person("One", 1);

// Create a second person from the JSON representation
// of the first (NOTE: assert it is of type Person!)
var p2: Person = <Person>JSON.parse(JSON.stringify(p));

document.writeln("Start");

document.writeln(p.name);  // OK: One
document.writeln(p.Age()); // OK: 1

document.writeln(p2.name); // OK: One
document.writeln(p2.age;   // OK: 1
document.writeln(p2.Age()); // ERROR: no method Age() on …
Run Code Online (Sandbox Code Playgroud)

json typescript

12
推荐指数
2
解决办法
2万
查看次数

标签 统计

json ×1

typescript ×1