Enforce Property Types with a Proxy
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Write typed(schema, initial), where schema maps each allowed key to a type name: "string", "number", "boolean" or "integer" (a number with no fractional part), and initial is an optional object of starting values, an empty object by default. Return a Proxy around a new object holding a copy of initial, so later changes never touch initial itself. Assigning a value checks it first: a key that isn't in the schema, or a value of the wrong type, throws a TypeError whose message includes the key, and leaves the object unchanged. A value of the right type is stored. initial is checked the same way, so typed throws a TypeError for a bad starting value or an unknown key.
Your code must pass
- Starts with a copy of the initial values
- Accepts values of the right type
- Throws a TypeError for the wrong type
- Throws a TypeError for unknown keys
- Treats integer as whole numbers only
- Checks the initial values too