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.

2
  • 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) but you can't count on it. There's going to be some redundancy needed if you really care about excess properties Commented Dec 27, 2020 at 4: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. stackoverflow.com/questions/31829951/… Commented Dec 28, 2020 at 1:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.