2

I've assigning to a partial in the constructor works really well, however it can write extra properties (if the object we pass into the data has a property which class T does not, it still gets copied)

    id: number
    username: string
    ....

    constructor(data: Partial<T>)
    {
        Object.assign(this, data)
    }

How can I avoid this? Object.keys(this) is empty when called in the constructor, so I cannot properly compare keys.

Jordan
  • 440
  • 2
  • 5
  • 14
  • 1
    You need an explicit list of the keys you want to copy. Uninitialized properties may or may not show up at runtime (depending on [compiler flags](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier)) but you can't count on it. There's going to be some redundancy needed if you really care about excess properties – jcalz Dec 27 '20 at 04:36
  • @jcalz I think I'll just go with assigning all my values to undefined. Not ideal, but it seems to initialize all the keys. https://stackoverflow.com/questions/31829951/how-to-reduce-javascript-object-to-only-contain-properties-from-interface – Jordan Dec 28 '20 at 01:47

0 Answers0