我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?

我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。

更新:你可以将它转换为typescript接口!


当前回答

使用从接口扩展的类。

然后:

    Object.assign(
        new ToWhat(),
        what
    )

和最好的:

    Object.assign(
        new ToWhat(),
        <IDataInterface>what
    )

ToWhat成为DataInterface的控制器

其他回答

你可以用一个tapi.js! 这是一种轻便的自动装置,可以双向工作。

npm i -D tapi.js

然后你就可以简单地做了

let typedObject = new YourClass().fromJSON(jsonData)

或者用承诺

axios.get(...).as(YourClass).then(typedObject => { ... })

你可以在文档里读到更多。

假设json具有与typescript类相同的属性,你不需要将json属性复制到typescript对象中。你只需要在构造函数中传递json数据来构造Typescript对象。

在你的ajax回调中,你会收到一个company:

onReceiveCompany( jsonCompany : any ) 
{
   let newCompany = new Company( jsonCompany );

   // call the methods on your newCompany object ...
}

为了使它起作用:

1)在Typescript类中添加一个构造函数,将json数据作为参数。在该构造函数中,使用jQuery扩展json对象,如下所示:extend(this, jsonData)。美元。扩展允许保留javascript原型,同时添加json对象的属性。

2)注意你必须对链接对象做同样的事情。在本例中的Employees中,还创建了一个构造函数,用于接收Employees的json数据部分。你调用$。将json雇员转换为typescript雇员对象。

export class Company
{
    Employees : Employee[];

    constructor( jsonData: any )
    {
        $.extend( this, jsonData);

        if ( jsonData.Employees )
            this.Employees = $.map( jsonData.Employees , (emp) => {
                return new Employee ( emp );  });
    }
}

export class Employee
{
    name: string;
    salary: number;

    constructor( jsonData: any )
    {
        $.extend( this, jsonData);
    }
}

这是我在处理Typescript类和json对象时发现的最佳解决方案。

使用“as”声明:

const data = JSON.parse(response.data) as MyClass;

我有同样的问题,我已经找到了一个库,可以做这项工作:https://github.com/pleerock/class-transformer。

它是这样工作的:

let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;

它支持嵌套的子类,但是你必须修饰你的类成员。

将对象原样传递给类构造函数;没有约定或检查

interface iPerson {
   name: string;
   age: number;
}

class Person {
   constructor(private person: iPerson) { }

   toString(): string {
      return this.person.name + ' is ' + this.person.age;
   }  
}


// runs this as // 
const object1 = { name: 'Watson1', age: 64 };
const object2 = { name: 'Watson2' };            // age is missing

const person1 = new Person(object1);
const person2 = new Person(object2 as iPerson); // now matches constructor

console.log(person1.toString())  // Watson1 is 64
console.log(person2.toString())  // Watson2 is undefined