Sean
Sean

Reputation: 655

Typescript dynamically assign class properties

I was wondering if there was a way to assign class properties via looping/Object.assign, for example something like:

interface Foo {
    b: string
    a: string
    r: number
}

class Example implements Foo {
    constructor(ref: Foo) {
        Object.assign(this, ref)
    }
}

-- Edit -- Error:

Class 'Example' incorrectly implements interface 'Foo'. Type 'Example' is missing the following properties from type 'Foo': b, a, r

Upvotes: 1

Views: 81

Answers (1)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9903

You can dynamically assign class properties by Object.assign, but the error you have get does not relate to Object.assign. That is happened because you incorrectly implemented the Foo interface. Here is correct implementation:

interface Foo { b: string a: string r: number }

class Example implements Foo {
    constructor(ref: Foo) {
        Object.assign(this, ref)
    }
   b!: string;//correct implementation
   a!: string;//correct implementation
   r!: number;//correct implementation
}

Note that you also can have base class instead of interface like this (and extends the base class):

class BaseFoo {
    b!: string
    a!: string
    r!: number
}

class BaseExample extends BaseFoo {
    constructor(ref: Foo) {
        super();
        Object.assign(this, ref)
    }
}

In this case you don't repeat the properties

PlaygroundLink

Upvotes: 2

Related Questions