【发布时间】:2018-07-14 22:47:36
【问题描述】:
在日常生活中,我需要从 ajax 读取一些 json 并将其转换为一些 Typed 对象(包括它的 METHODS)。在互联网上,我发现并使用以下代码进行类型转换:
export class Obj
{
public static cast<T>(obj, type: { new(...args): T} ): T
{
obj.__proto__ = type.prototype;
return obj;
}
}
例如,它可以通过以下方式使用:
let objFromJson = { id: 666, name: "love" };
let building: Building = null;
building = Obj.cast(objFromJson, Building);
// On this point constructor for Building is not call - this is
// correct because we not create object but only make type casting
building.test('xx');
// on this point on console we should get:
// > "building.test a:xx, name:love"
// so object 'building' indeed have methods of Building Class
哪里(例子来自'head')
export class Building {
constructor(
public id: number,
public name: string,
) {
console.log('building.constructor: id:' + id + ', name' + name);
}
public test(a) {
console.log('building.test a:' + a + ', name:' + this.name);
}
}
附加信息:我们可以只使用cast<T>(obj, type): T 而不是使用cast<T>(obj, type: { new(...args): T} ): T,但我读到第二个版本会导致箭头函数出现问题(https://stackoverflow.com/a/32186367/860099)-我不明白为什么-?
问题:我不太了解 Obj.cast 方法的工作原理(例如,我如何在调用它时使用 ...args) - 有人可以解释一下吗?有人知道替代函数,但不是用于强制转换,而是用于 CREATE 对象(所以调用构造函数)以类似方便的方式形成 json 数据(例如building = Obj.create(objFromJson, Building);
【问题讨论】:
标签: json typescript casting