1

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:

enter image description here

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))
    }
}
ymerej
  • 727
  • 1
  • 8
  • 21
  • I don't think "assert" is the right word here. Maybe "construct" or "instantiate"? – jcalz Nov 06 '19 at 19:27
  • short answer: converting nested plain javascript objects to class instances takes work that cannot be avoided. There may be libraries that will do that work for you, but they will likely require you to add metadata so the required copying will happen at runtime. ‍♂️ – jcalz Nov 06 '19 at 20:03
  • @jcalz look up "typescript assertion": https://www.tutorialsteacher.com/typescript/type-assertion – ymerej Nov 06 '19 at 21:04
  • A type assertion has no runtime effect; it's just a way to tell the compiler something it doesn't already know about the type of a value. What you're doing is *not* an assertion; you're actually constructing instances of a class, at runtime. That's why I'm saying "assert" isn't the right word. – jcalz Nov 07 '19 at 01:55
  • I'm sorry my responses have not satisfied you. Could you point out where in your code you are doing a type assertion, as described in the [TypeScript Handbook documentation for type assertions](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions)? There are several ways to write type assertions in TypeScript. One is using a type in angle brackets before a value, such as ` persons`. Another is with `as` after the value, such as `persons as Person`. I don't see such assertions anywhere, but maybe I'm missing something. – jcalz Nov 07 '19 at 16:04

0 Answers0