1

Having this code:

interface MyInterface {
    readonly valA: number;
    readonly valB: number;
}

class MyClass {
    readonly valA: number;
    readonly valB: number;

    constructor(props: MyInterface) {
        this.valA = props.valA;
        this.valB = props.valB;
    }
}

const myClassInstance = new MyClass({valA: 1, valB: 2});

console.log(myClassInstance.valA);
console.log(myClassInstance.valB);

How would one use the object as send into the constructor to set the instance attributes more effectively. This "feels" wrong, as a mistake can be made pretty easy when not matching data types correctly, and it "feels" like code duplication as well.

I am asking this is now I need to duplicate all attributes defined in the Interface as class attribute. This works in this case where there are only 2, but could become cumbersome if there were 10 or more.

An other requirement would be that the fields as described in the interface could possibly be optional (readonly valA?: number;).

I would still like to access the attributes as now in the log statements.

Is what I am asking for possible?

1 Answer 1

2

From this answer, TypeScript allows for class/interface merging.

interface MyInterface {
    readonly valA?: number;
    readonly valB?: number;
}

interface MyClass extends MyInterface { }
class MyClass {
    // readonly valA: number;
    // readonly valB: number;

    constructor(props: MyInterface) {
            // Cannot assign this way due to readonly properties
                // this.valA = props.valA;
                // this.valB = props.valB;
            Object.assign(this, props);
    }
}

const myClassInstance = new MyClass({valA: 1, valB: 2});

console.log(myClassInstance.valA);
console.log(myClassInstance.valB);
Sign up to request clarification or add additional context in comments.

Comments

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.