我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?
我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。
更新:你可以将它转换为typescript接口!
我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?
我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。
更新:你可以将它转换为typescript接口!
当前回答
如果你正在使用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。
它是这样工作的:
let jsonObject = response.json() as Object;
let fooInstance = plainToClass(Models.Foo, jsonObject);
return fooInstance;
它支持嵌套的子类,但是你必须修饰你的类成员。
目前还没有自动检查从服务器接收到的JSON对象是否具有预期的(读取是否符合)typescript的接口属性。但是你可以使用用户定义的类型保护
考虑以下接口和一个愚蠢的json对象(它可以是任何类型):
interface MyInterface {
key: string;
}
const json: object = { "key": "value" }
三种可能的方法:
A.类型断言或放置在变量之后的简单静态强制转换
const myObject: MyInterface = json as MyInterface;
B.简单的静态铸造,前变量和菱形之间
const myObject: MyInterface = <MyInterface>json;
C.高级动态转换,你检查自己的对象结构
function isMyInterface(json: any): json is MyInterface {
// silly condition to consider json as conform for MyInterface
return typeof json.key === "string";
}
if (isMyInterface(json)) {
console.log(json.key)
}
else {
throw new Error(`Expected MyInterface, got '${json}'.`);
}
你可以玩一下这个例子
注意,这里的困难在于编写isMyInterface函数。我希望TS迟早会添加一个装饰器,将复杂的类型导出到运行时,并让运行时在需要时检查对象的结构。现在,您可以使用json模式验证器,其目的与此大致相同,也可以使用此运行时类型检查函数生成器
使用“as”声明:
const data = JSON.parse(response.data) as MyClass;
如果你需要将json对象转换为typescript类,并在结果对象中使用它的实例方法,你需要使用object。setPrototypeOf,就像我在下面的代码片段中所做的那样:
Object.setPrototypeOf(jsonObject, YourTypescriptClass.prototype)
对我来说,这很有效。我使用函数 对象。分配(目标,源…)。 首先,创建正确的对象,然后将数据从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;
}
}