Skip to content

Instantly share code, notes, and snippets.

@emolr
Last active August 16, 2017 11:50
Show Gist options
  • Save emolr/9dd8ac49f39c1d6bf5872e7955deecd6 to your computer and use it in GitHub Desktop.
Save emolr/9dd8ac49f39c1d6bf5872e7955deecd6 to your computer and use it in GitHub Desktop.
const data = {
title: 'hello world',
endTime: 123456,
foo: [1, 2, 3]
};
const properties = {
title: 'string',
endTime: 'number',
foo: 'array'
};
/**
* Has prop types checker
* Checks if necessary keys and types are present in object.
* the object can contain more keys than the ones being checked for.
*
* @param obj
* @param expected - {key: 'string|boolean|object|array|number|symbol|function'}
* @return {boolean}
*/
const hasPropTypes = (obj, expected) => {
if (typeof obj !== 'object' || obj === null) {
return false;
};
return Object.keys(expected).every(key => {
if (!obj.hasOwnProperty(key)) {
return false;
}
switch (expected[key]) {
case 'array':
return Array.isArray(obj[key]);
default:
return typeof obj[key] === expected[key]
}
});
};
console.log(hasPropTypes(data, properties));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment