The Aim

I want the objects I use in my TypeScript code to let me set multiple properties on them in one go. My objects must have a method setPropssuch that when given a properly typed map of properties, the method sets the corresponding properties on the objects.

The Approach

I have a base class, say BaseObject, that has the publicsetProps method. setProps must take parameters that are compatible with the instance of a class derived from BaseClass. This is achieved with generics. The method will look like the following piece of code:

I constrain the type parameter T to represent a type that inherits from BaseObject by using the syntax <T extends BaseObject>.

Now, I want to assign the properties of the passed parameter to the object on which setProps was called. To achieve this, I proceed as shown in the following excerpt:

The for in loop gets all the keys in values and for each such property, if its value is not null, assigns it to the same property on the calling object.

#generics #typescript #mapped-types

Smart Typescript Bulk Property Assignment
2.95 GEEK