Consider the following code snippet:
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);
Is there a more efficient way to set the instance attributes using the object passed into the constructor? The current method feels error-prone when data types don't match and seems redundant with potential for code duplication.
I'm facing a situation where I need to replicate all Interface attributes as class attributes, which works fine for two attributes but could get complicated with ten or more.
Additionally, some fields in the interface might need to be optional (readonly valA?: number;
).
Ultimately, I still want to access the attributes as shown in the log statements. Is there a solution to meet these requirements?