1

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

3
  • what is wrong with Object.assign? Commented Sep 26, 2021 at 4:45
  • Hi @AlirezaAhmadi I get an error saying the properties from Foo aren't implemented Commented Sep 26, 2021 at 5:26
  • I made an answer for you and put the playground link to see modified code Commented Sep 26, 2021 at 7:24

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Using a base class instead of an interface is exactly what I was looking for, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.