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?