Skip to content

Instantly share code, notes, and snippets.

@sag1v sag1v/typeCheck.js
Last active Jul 4, 2019

Embed
What would you like to do?
A run-time type checker with proxies
function typeCheck(obj, definition) {
return new Proxy(obj, {
set(obj, key, value) {
if (key in definition && typeof value !== definition[key]) {
throw new TypeError(`Invalid type of ${key} '${typeof value}'. expected to be '${definition[key]}'`)
}
return Reflect.set(obj, key, value);
}
});
}
const userShape = {
name: 'string',
age: 'number'
}
class TypeSafe{
constructor(shape){
return typeCheck(this, shape);
}
}
class User extends TypeSafe{
constructor(name, age){
super(userShape);
this.name = name;
this.age = age;
}
}
let myUser = new User('sagiv', '36'); // throws -> TypeError: Invalid type of age 'string'. expected to be 'number'
// support nested objects
function typeCheck(obj, definition) {
const validator = {
set(obj, key, value) {
if (key in definition) {
if (Object.prototype.toString.call(value) === "[object Object]") {
// this is an object
Object.entries(value).forEach(([oKey, oVal]) => {
// proxy the set of each key
const nested = typeCheck(value, definition[key]);
Reflect.set(nested, oKey, oVal);
});
} else if (typeof value !== definition[key]) {
throw new TypeError(`Invalid type of ${key} '${typeof value}'. expected to be '${definition[key]}'`)
}
}
return Reflect.set(obj, key, value);
}
}
return new Proxy(obj, validator);
}
const userShape = {
name: 'string',
age: 'number',
address: {
where: 'string'
}
}
class TypeSafe {
constructor(shape) {
return typeCheck(this, shape);
}
}
class User extends TypeSafe {
constructor(name, age, address) {
super(userShape);
this.name = name;
this.age = age;
this.address = address;
}
}
let myUser = new User('sagiv', 36, {
where: 0
}); // throws -> TypeError: Invalid type of where 'number'. expected to be 'string'
@sag1v

This comment has been minimized.

Copy link
Owner Author

sag1v commented Mar 14, 2019

TODO: add complex objects support

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.