I need to ensure that the constructor parameter is validated correctly when an instance of a class is created.
The parameter must be an object that contains exactly all the properties, with the appropriate types as specified in the class definition.
If the data does not match these criteria, I want TypeScript to flag it as a mismatch.
class User {
username: string;
// more properties
constructor(data:object) {
// Validate if data object exactly matches all class properties and their types
// Set instance properties
}
};
// Desired Output
new User(); // "data parameter missing";
new User(45); // "data parameter is not of type object";
new User(); // "username Property missing!";
new User({username:"Michael"}); // Valid;
new User({username:43}); // "username is not of type string";
new User({username:"Michael", favoriteFood: "Pizza"}); // "favoriteFood is not a valid property";
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "es2015",
"lib": [
"es2016.array.include"
],
"downlevelIteration": true,
"strict": true
}
}