Create a function `createValidatedObject(schema)` that returns a Proxy which validates property assignments against the schema types.
Problem Statement
Create a function `createValidatedObject(schema)` that returns a Proxy which validates property assignments against the schema types.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Proxy intercepts operations on an object (get, set, etc.).
š” Hint 2:
Use the set trap to validate the type before allowing assignment.
š” Hint 3:
Check typeof value against schema[prop] in the set handler.
ā
Solution:
```javascript
function createValidatedObject(schema) {
return new Proxy({}, {
set(target, prop, value) {
if (schema[prop] && typeof value !== schema[prop]) {
throw new TypeError(`${prop} must be ${schema[prop]}`);
}
target[prop] = value;
return true;
}
});
}
```