DEV Community

Cover image for Strict object type using Proxy in JavaScript
Hidayt Rahman
Hidayt Rahman

Posted on

Strict object type using Proxy in JavaScript

Javascript object field can be overwrited by any data types. Can we strict it? yes of course we can strict it with the help of Proxy.

Example

We have employee object which has some related keys

const employee = {
 name: "hidayt rahman",
 salary: 12000,
 isActive: true,
}
Enter fullscreen mode Exit fullscreen mode

We can overwrite the value with any data types.
for example we can set salary with string value and JS will not complain any error because this is how it works.

employee.salary = "12000" // it will overwrite number with string value
Enter fullscreen mode Exit fullscreen mode

Sadly, This is not weird for javascript, but its buggy if we are not using Typescript, So here is the solution in JS itself using Proxy

lets create a target object where we will be using set to configure the object keys according to the requirements.

We will restrict data type for salary and name field that will only accept valid data type.

  • Name will only accept string
  • Salary will not accept non integer data

const target = {
    set(target, prop, value) {

        if (prop in target) {
            if (prop === 'name' && typeof value !== 'string') {
                throw new Error(`Type '${typeof value}' is not assignable to type 'string' for '${prop}' field.`);

            }

            if (prop === 'salary' && typeof value !== 'number') {
                throw new Error(`Type '${typeof value}' is not assignable to type 'number' for '${prop}' field.`);

            }

             return target[prop] = value;

        } else {
            throw new Error(`'${prop}' is not a valid prop`)
        }
    }

}

const strictedEmployee = new Proxy(employee, target);

Enter fullscreen mode Exit fullscreen mode

Now if we use the strictedEmployee proxy object and set salary with non numeric data type, it will throw an error.

strictedEmployee.salary = "2000";
Enter fullscreen mode Exit fullscreen mode

Uncaught Error: Type 'string' is not assignable to type 'number' for 'salary' field

Uncaught Error: Type 'string' is not assignable to type 'number' for 'salary' field.

Oldest comments (0)