Home > Back-end >  Typescript dynamically assign class properties
Typescript dynamically assign class properties

Time:09-27

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

CodePudding user response:

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

  • Related