Reputation: 12025
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
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