Skip to content

Instantly share code, notes, and snippets.

@huttj
Created February 20, 2015 22:16
Show Gist options
  • Save huttj/4911c329a8cc1e96959b to your computer and use it in GitHub Desktop.
Save huttj/4911c329a8cc1e96959b to your computer and use it in GitHub Desktop.
Type enforcement in JavaScript
function User(data) {
this.name = is(String)(data.name);
}
function is(obj) {
return function(val) {
if (val === null || val.constructor !== obj) {
throw [
'Invalid type specified; expected:',
obj.name + ',',
'got:',
(val && val.constructor && val.constructor.name) || 'null'
].join(' ');
}
return val;
}
}
var user = new User({name: 'James'});
console.log(user); // { name: 'James' }
console.log(user.constructor.name) // User
new User({name: null}); // Invalid type specified; expected: String, got: null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment