一个有趣的任务。
我开始:
import React from "react";
import * as PropTypes from "prop-types";
function Hello(props) {
const { boo, foo } = props;
return (
<div>
<h1>{boo}</h1>
<h2>{foo}</h2>
</div>
);
}
Hello.propTypes = {
boo: PropTypes.string,
foo: PropTypes.number
};
export default Hello;
我发现这篇文章https://blog.jim-nielsen.com/2020/proptypes-outside-of-react-in-template-literal-components/有功能:
/**
* Anytime you want to check prop types, wrap in this
* @param {function} Component
* @param {Object} propTypes
* @return {string} result of calling the component
*/
function withPropTypeChecks(Component) {
return props => {
if (Component.propTypes) {
Object.keys(props).forEach(key => {
PropTypes.checkPropTypes(
Component.propTypes,
props,
key,
Component.name
);
});
}
return Component(props);
};
}
然后我又写了一篇:
const getPropsInfo = (component) => {
const result = {};
const mock = Object.keys(component.propTypes).reduce(
(acc, p) => ({ ...acc, [p]: Symbol() }),
{}
);
const catching = (arg) => {
const [, , prop, type] = `${arg}`.match(
/Warning: Failed (.*) type: Invalid .* `(.*)` of type `symbol` supplied to.*, expected `(.*)`./
);
result[prop] = type;
};
const oldConsoleError = console.error.bind(console.error);
console.error = (...arg) => catching(arg);
withPropTypeChecks(component)(mock);
console.error = oldConsoleError;
return result;
};
我选择 Symbol 作为不太期望的类型。
并称它为:
const propsInfo = getPropsInfo(Hello);
console.log(propsInfo);
结果我得到:{boo: "string", foo: "number"}
P.S.:我还没有在其他类型上测试过。只是为了好玩! :)