Skip to content

Instantly share code, notes, and snippets.

@gilbarbara
Created January 16, 2019 00:44
Show Gist options
  • Save gilbarbara/b891aac1f539fd657232389570e83eb8 to your computer and use it in GitHub Desktop.
Save gilbarbara/b891aac1f539fd657232389570e83eb8 to your computer and use it in GitHub Desktop.
WIP: get type from a React component propTypes
const React = require('react');
const PropTypes = require('prop-types');
class Component extends React.Component {
render() {
return React.createElement('h1', {}, 'Component!');
}
}
Component.propTypes = {
name: PropTypes.string.isRequired,
type: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
const primitiveTypes = [
{ name: 'array', value: [] },
{ name: 'boolean', value: true },
{ name: 'function', value: () => {} },
{ name: 'number', value: 1 },
{ name: 'object', value: {} },
{ name: 'string', value: '' },
{ name: 'symbol', value: Symbol() }
];
function getPropType(propTypes, propName, name) {
const propErrors = [];
const acceptedTypes = [];
const consoleError = console.error;
primitiveTypes.forEach(d => {
const props = {
[propName]: d.value,
};
console.error = error => propErrors.push({ type: d.name, error });
PropTypes.checkPropTypes(propTypes, props, 'prop', name);
console.error = consoleError;
if (!propErrors.find(e => e.type === d.name)) {
acceptedTypes.push(d.name);
}
});
return acceptedTypes.join(' | ');
}
function getPropIsRequired(propTypes, propName) {
const propErrors = [];
const props = {
[propName]: null,
};
console.error = error => propErrors.push(error);
let error = PropTypes.checkPropTypes(propTypes, props);
const consoleError = console.error;
return !!propErrors.length;
}
function extractTypes(component) {
const typesMap = [];
const { displayName, propTypes } = component.type;
if (!Object.keys(propTypes).length) {
return typesMap;
}
Object.keys(propTypes).forEach(propName => {
typesMap.push({
key: propName,
type: getPropType(propTypes, propName, displayName),
required: getPropIsRequired(propTypes, propName, displayName),
});
});
return typesMap;
}
console.log(extractTypes(<Component />));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment