In my TypeScript project, I'm creating a class with constructor parameters defined by an interface to limit the properties to only those that are specified.
Although the current code snippet achieves the desired functionality, I am looking for a way to streamline it and eliminate repetition. Each property is mentioned 4 times in the code, which seems redundant. Is there a more efficient approach?
interface MyInterface {
property1: string;
property2: boolean;
property3: number;
}
class MyClass {
property1: string;
property2: boolean;
property3: number;
constructor(parameters: MyInterface) {
this.property1 = parameters.property1;
this.property2 = parameters.property2;
this.property3 = parameters.property3;
}
}
const example = new MyClass({property1: "Property 1", property2: true, property3: 3, extraProperty: "Shouldn't exist"});
console.log(example);
UPDATE: Additionally, I need to ensure that the properties are restricted at run-time to prevent objects with unknown additional properties.