Last active
June 12, 2018 08:57
-
-
Save fedecarg/fabe9db498b84a46d9894aee3aa02688 to your computer and use it in GitHub Desktop.
Another way to type javascript objects
This file contains hidden or 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
| /** | |
| * 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