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

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

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


当前回答

使用从接口扩展的类。

然后:

    Object.assign(
        new ToWhat(),
        what
    )

和最好的:

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

ToWhat成为DataInterface的控制器

其他回答

我发现了一篇关于将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

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

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

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

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

有几种方法可以做到这一点,让我们来看看一些选项:

class Person {
   id: number | undefined;
   firstName: string | undefined;
   //? mark for note not required attribute.
   lastName?: string;
}

// Option 1: Fill any attribute and it would be accepted.
const person1= { firstName: 'Cassio' } as Person ;
console.log(person1);

// Option 2. All attributes must assign data.
const  person2: Person = { id: 1, firstName: 'Cassio', lastName:'Seffrin' };  
console.log(person2);

//  Option 3. Use partial interface if all attribute not required.
const  person3: Partial<Person> = { firstName: 'Cassio' };  
console.log(person3);

//  Option 4. As lastName is optional it will work
const  person4: Person = { id:2, firstName: 'Cassio'  };
console.log(person4);

//  Option 5. Fill any attribute and it would be accepted.
const person5 = <Person> {firstName: 'Cassio'}; 
console.log(person5 );

结果:

[LOG]: {
  "firstName": "Cassio"
} 
[LOG]: {
  "id": 1,
  "firstName": "Cassio",
  "lastName": "Seffrin"
} 
[LOG]: {
  "firstName": "Cassio"
} 
[LOG]: {
  "id": 2,
  "firstName": "Cassio"
} 
[LOG]: {
  "firstName": "Cassio"
} 

如果你有一个接口而不是Typescript类,它也可以工作。

interface PersonInterface {
   id: number;
   firstName: string;
   lastName?: string;
}

播放这个代码

在后期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://jvilk.com/MakeTypes/

您可以使用该网站为您生成代理。它生成一个类,可以解析和验证输入的JSON对象。