typescript - Angular 4 การถอดรหัส Json ของ Http และชนิดทั่วไป
ฉันมี API ที่ส่งกลับวัตถุ JSON เหมือนตัวอย่างด้านล่าง:
{
"name": "testing",
"theme": "something"
"themeProperties": {}
}
ประเภทของอ็อบเจ็กต์ที่ themeProperties มีจะแตกต่างกันไปขึ้นอยู่กับค่าของ theme ฉันกำลังพยายามกำหนดประเภทเหล่านี้แบบนี้:
export class Config<T> {
public name: string;
public theme: string;
public themeProperties: T
}
export class Style1Props extends Config<Style1Props> {
public fooProp1: number;
public fooProp2: boolean
}
export class Style2Props implements Config<Style2Props> {
public barProp1: any;
public barProp2: string;
public createdDate: Date;
}
public class ConfiService {
public getConfig<T>() : T {
}
}
และฉันจะใช้สิ่งนี้ในคอมโพเนนต์ของฉันเหมือนกับ:
let config = this.configService.getConfig<StyleProps2>()
ปัญหาของฉันคือข้อมูลทั้งหมดของฉันมาจาก API และคลาสไม่ได้เป็นชนิดข้อมูลพื้นฐานที่ง่าย ๆ พวกมันมีอาเรย์และคลาสอยู่ภายใน (โดยเฉพาะ Date) และเนื่องจากการทำ deserialization เริ่มต้นไม่ทำให้เมธอดเหล่านั้นสามารถใช้งานได้ ฉันได้ค้นคว้าเครื่องมือ deserialization สำหรับ TypeScript หลายตัวแต่ไม่มีตัวไหนที่ทำงานกับ generics ได้ แล้วฉันจะทำการ deserialization (อย่างลึก) ของคลาสและสมาชิกภายในของมันอย่างไร?