facebook / prop-types

Runtime type checking for React props and similar objects
MIT License
4.48k stars 356 forks source link

add `getPropTypeDefinitions' function #172

Closed ambewas closed 6 years ago

ambewas commented 6 years ago

This PR introduces getPropTypeDefinitions on the prop-types package.

what?

getPropTypeDefinitions can be called in development, to return an object containing all the prop types defined on a specific component, along with an array of expected values (for enum types or instance's).

why?

Being able to callgetPropTypeDefinitions is especially useful in some higher order components.

My own use case is for a wireframing tool that uses actual react-components as building blocks. In one of the higher order components, I need access to the different props of a wrapped component so they can be exposed in a UI, to allow editing of these props and reviewing the changes in real time.

This functionality could also be useful for react dev-tools to allow better insight in props and expected props.

example

const SomeComponent = (props) => <div {...props}>foobar</div>;
SomeComponent.propTypes = {
    background: PropTypes.oneOf(["blue", "red"]),
    color: PropTypes.string,
    onClick: PropTypes.func,
    someShape: PropTypes.shape({
        bar: PropTypes.bool,
        baz: PropTypes.oneOf(["shoe", "store"]),
        boe: PropTypes.shape({
            lala: PropTypes.number,
        }),
    }),
};
const propTypeDefinitions = PropTypes.getPropTypeDefinitions(SomeComponent.propTypes);

// output:
{
    "background": {
        "type": "enum",
        "expectedValues": [
            "blue",
            "red"
        ]
    },
    "color": {
        "type": "string"
    },
    "onClick": {
        "type": "function"
    },
    "someShape": {
        "type": "shape",
        "shapeTypes": {
            "bar": {
                "type": "boolean"
            },
            "baz": {
                "type": "enum",
                "expectedValues": [
                    "shoe",
                    "store"
                ]
            },
            "boe": {
                "type": "shape",
                "shapeTypes": {
                    "lala": {
                        "type": "number"
                    }
                }
            }
        }
    }
}
gaearon commented 6 years ago

Thanks for the PR, but we explicitly discourage from giving PropTypes runtime semantics beyond DEV-time validation of React props. Partially because it lets people safely remove declarations in the production builds without worrying if other libs read them.

If you need something more powerful, coming up with your own separate system would be the best option.