Skip to content

Instantly share code, notes, and snippets.

@fedecarg
Last active June 12, 2018 08:57
Show Gist options
  • Select an option

  • Save fedecarg/fabe9db498b84a46d9894aee3aa02688 to your computer and use it in GitHub Desktop.

Select an option

Save fedecarg/fabe9db498b84a46d9894aee3aa02688 to your computer and use it in GitHub Desktop.
Another way to type javascript objects
/**
* Checks the data type of property and throws a TypeError if it's invalid.
*
* Usage:
*
* function test(options = {}) {
* checkObjectTypes(options, {'a':'String', 'b':'Number', 'c':'Array'});
* }
*
* @param {Object} obj
* @param {Object} types
*/
export default function checkObjectTypes(obj, types = {}) {
for (let prop in types) {
if (obj[prop] === undefined
|| (obj[prop].constructor.name !== types[prop] || Object.prototype.toString.call(obj[prop]) === -1)) {
throw new TypeError(`prop "${prop}" must be of type "${types[prop]}"`);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment