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

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

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


当前回答

在后期TS,你可以这样做:

const isMyInterface = (val: any): val is MyInterface => {
  if (!val) { return false; }
  if (!val.myProp) { return false; }
  return true;
};

而用户是这样的:

if (isMyInterface(data)) {
 // now data will be type of MyInterface
}

其他回答

在后期TS,你可以这样做:

const isMyInterface = (val: any): val is MyInterface => {
  if (!val) { return false; }
  if (!val.myProp) { return false; }
  return true;
};

而用户是这样的:

if (isMyInterface(data)) {
 // now data will be type of MyInterface
}

我发现了一篇关于将JSON转换为Typescript类的非常有趣的文章:

http://cloudmark.github.io/Json-Mapping/

你最终会得到如下代码:

let example = {
                "name": "Mark", 
                "surname": "Galea", 
                "age": 30, 
                "address": {
                  "first-line": "Some where", 
                  "second-line": "Over Here",
                  "city": "In This City"
                }
              };

MapUtils.deserialize(Person, example);  // custom class

如果你需要将json对象转换为typescript类,并在结果对象中使用它的实例方法,你需要使用object。setPrototypeOf,就像我在下面的代码片段中所做的那样:

Object.setPrototypeOf(jsonObject, YourTypescriptClass.prototype)

在TypeScript中,你可以使用接口和泛型进行类型断言,如下所示:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;

其中ILocationMap描述了数据的形状。这种方法的优点是JSON可以包含更多属性,但形状满足接口的条件。

但是,这不会添加类实例方法。

对我来说,这很有效。我使用函数 对象。分配(目标,源…)。 首先,创建正确的对象,然后将数据从json对象复制到目标。例子:

let u:User = new User();
Object.assign(u , jsonUsers);

还有一个更高级的使用例子。一个使用数组的例子。

this.someService.getUsers().then((users: User[]) => {
  this.users = [];
  for (let i in users) {
    let u:User = new User();
    Object.assign(u , users[i]);
    this.users[i] = u;
    console.log("user:" + this.users[i].id);
    console.log("user id from function(test it work) :" + this.users[i].getId());
  }

});

export class User {
  id:number;
  name:string;
  fullname:string;
  email:string;

  public getId(){
    return this.id;
  }
}