У меня есть следующий код Typescript:
class Foo {
private _id: number;
private _desc: string;
constructor(id: number, desc: string) {
this._id = id;
this._desc = desc;
}
public get id(): number {
return this.id;
}
public set id(value: number) {
this._id = value;
}
public get desc():string {
return this.desc;
}
public set desc(value: string) {
this._desc = value;
}
}
let foo = new Foo(1, 'something');
Я хотел бы получить строку из класса Typescript, я имею в виду с getter и setter. Тогда я должен получить следующую строку:
{"id":1,"desc":"something"}
Согласно этому ответу Я могу достичь этого, добавив в класс следующий метод:
public toJSONString(): string {
return JSON.stringify(this, Object.keys(this.constructor.prototype));
}
Работает.
Не работает, если класс Typescript содержит какой-либо другой подкласс.
Так что, если у меня есть следующий код:
class Foo {
private _id: number;
private _desc: string;
private _user: Bar;
constructor(id: number, desc: string, user: Bar) {
this._id = id;
this._desc = desc;
this._user = user;
}
public get id(): number {
return this._id;
}
public set id(value: number) {
this._id = value;
}
public get desc():string {
return this._desc;
}
public set desc(value: string) {
this._desc = value;
}
public get user(): Bar {
return this._user;
}
public set user(value: Bar) {
this._user = value;
}
public toJSONString(): string {
return JSON.stringify(this, Object.keys(this.constructor.prototype));
}
}
class Bar {
private _name: string;
private _surname: string;
constructor(name: string, surname: string) {
this._name = name;
this._surname = surname;
}
public get name(): string {
return this._name;
}
public set name(value: string) {
this._name = value;
}
public get surname():string {
return this._surname;
}
public set surname(value: string) {
this._surname = value;
}
}
let foo = new Foo(1, 'something', new Bar('foo', 'bar'));
Если я использую метод toJSONString
, я получаю следующую строку:
{"id":1,"desc":"something","user":{}}
вместо этого:
{"id":1,"desc":"something","user":{ "name": "foo", "surname": "bar"}}
Итак, как я могу получить строку из класса Typescript, который имеет другие подклассы?
(Если вам нужна здесь игровая площадка для первого кода и вот игровая площадка для второго кода)