POV
POV

Reputation: 12025

How to assign values to all properties of class in TypeScript?

I have a class with private properties:

class A implements IA {
   private id: number;
   private name: string;

   constructor(obj: IA) {
      // Set here properties from obj
   }
}

I want to pass object IA with initialized values when I create instance A, and refill only that properties in class, which I passed.

new A({id: 1}) or new A({id: 1, name: "O"})

How to do this in TypeScript?

Upvotes: 4

Views: 4871

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

The simplest way to do this is to just use Object.assign. It will only copy the fileds specified in the constructor parameter.

interface IA{
    id? : number;
    name? : string
}

class A {
    private id: number;
    private name: string;

    constructor(obj: IA) {
        Object.assign(this, obj)
    }
}

Note I removed the implements from the class since private fields can't be the implentation for an interface

Upvotes: 10

Related Questions