我从远程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
}

其他回答

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

它是这样工作的:

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

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

如果你正在使用ES6,试试这个:

class Client{
  name: string

  displayName(){
    console.log(this.name)
  }
}

service.getClientFromAPI().then(clientData => {
  
  // Here the client data from API only have the "name" field
  // If we want to use the Client class methods on this data object we need to:
  let clientWithType = Object.assign(new Client(), clientData)

  clientWithType.displayName()
})

但遗憾的是,这个方法对嵌套对象不起作用。

我在这里使用这个库:https://github.com/pleerock/class-transformer

<script lang="ts">
    import { plainToClass } from 'class-transformer';
</script>

实现:

private async getClassTypeValue() {
  const value = await plainToClass(ProductNewsItem, JSON.parse(response.data));
}

有时必须解析plainToClass的JSON值才能理解它是JSON格式的数据

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

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

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

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

你不能简单地将Ajax请求的原始JavaScript结果转换为典型的JavaScript/TypeScript类实例。有许多技术可以做到这一点,通常涉及到复制数据。除非创建类的实例,否则它不会有任何方法或属性。它仍然是一个简单的JavaScript对象。

而如果你只处理数据,你可以只做一个转换到一个接口(因为它是一个纯粹的编译时结构),这将需要你使用一个TypeScript类,它使用数据实例并对该数据执行操作。

一些复制数据的例子:

将AJAX JSON对象复制到现有对象 在JavaScript中将JSON字符串解析为特定对象原型

本质上,你只需要:

var d = new MyRichObject();
d.copyInto(jsonResult);