Is there a quick way to assert nested objects in typescript? For example see the following code:
class Person {
name: string = '';
age: number = 0;
constructor(init?: Partial<Person>) {
Object.assign(this, init);
}
}
class Group {
name: string = '';
persons: Array<Person> = [];
constructor(init?: Partial<Group>) {
Object.assign(this, init);
}
}
const test = {
name: 'Justice League',
persons: [
{ name: 'Batman', age: 35 },
{ name: 'Superman', age: 42}
]
}
const result = new Group(test);
console.log(result);
I can see Group get's properly asserted but the array of persons does not:
Am I forced to loop through the array and individually assert each? Like so:
class Group {
name: string = '';
persons: Array<Person> = [];
constructor(init?: Partial<Group>) {
Object.assign(this, init);
this.persons = this.persons.map(p => new Person(p))
}
}