Skip to content

Instantly share code, notes, and snippets.

@amasad
Created January 5, 2017 20:22
Show Gist options
  • Save amasad/11f0e98193ef43d12c584d6b7c25b853 to your computer and use it in GitHub Desktop.
Save amasad/11f0e98193ef43d12c584d6b7c25b853 to your computer and use it in GitHub Desktop.
Given a React component props, generate potential react propTypes
const topLevelBlacklist = [
'children',
'history',
'location',
'params',
'route',
'routeParams',
'routes',
];
function genIndent(indent) {
let s = '';
for (let i = 0; i < indent; i++) {
s += ' ';
}
return s;
}
function genProps(props, indent, blacklist = null) {
let s = '';
for (const p in props) {
if (blacklist && blacklist.includes(p)) {
continue;
}
const t = sniff(props[p], indent);
if (!t) {
continue;
}
s += genIndent(indent);
s += `${p}: `;
s += t;
s += ',\n';
}
return s;
}
function sniff(prop, indent) {
if (typeof prop === 'string') {
return 'React.PropTypes.string';
}
if (typeof prop === 'number') {
return 'React.PropTypes.number';
}
if (typeof prop === 'boolean') {
return 'React.PropTypes.bool';
}
if (typeof prop === 'function') {
return 'React.PropTypes.func';
}
if (typeof prop === 'symbol') {
return 'React.PropTypes.symbol';
}
if (Array.isArray(prop)) {
if (prop.length) {
const t = sniff(prop[0], indent + 1);
if (t) {
return 'React.PropTypes.arrayOf(\n' +
genIndent(indent + 1) + sniff(prop[0], indent + 1) +
',\n' + genIndent(indent) + ')';
}
}
return 'React.PropTypes.array';
}
if (prop === null) {
return false;
}
if (typeof prop === 'object') {
if (Object.keys(prop).length) {
let s = 'React.PropTypes.shape({\n';
s += genProps(prop, indent + 1);
s += genIndent(indent);
s += '})';
return s;
}
return 'React.PropTypes.object';
}
throw new Error(`unkown type: ${typeof prop}`);
}
module.exports = (props) => {
let propTypes = 'static propTypes = {\n';
propTypes += genProps(props, 1, topLevelBlacklist);
propTypes += '}';
return propTypes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment