Created
February 20, 2015 22:16
-
-
Save huttj/4911c329a8cc1e96959b to your computer and use it in GitHub Desktop.
Type enforcement in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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