How to configure proptypes for interface in react typescript

Viewed 934

How would one go about informing PropTypes of the appropriate type if a property that is an interface?
Requirements - Using both TS and PropTypes.
Goal - something more accurate than PropTypes.any that passes standard eslint and tslint.
Limitation - Cannot bring in additional packages to generate it or do it for me somehow

import React from "react";
import PropTypes from "prop-types";

interface Test {
  a: string;
  b: string;
}
interface TestProps {
  test: Test;
  other: string;
}

const tester: React.FC<TestProps> = (props) => <div>{JSON.stringify(props.test)}</div>;

tester.propTypes = {
  other: PropTypes.string.isRequired,
  test: PropTypes.any.isRequired
};

export default tester;
1 Answers

This may not exactly be what you are looking for because I use type instead of interface, but I would do it the other way round - infer type from PropTypes using PropTypes.InferProps. This saves me from having to manually create both.

import React from "react";
import PropTypes from "prop-types";

const propTypes = {
  test: PropTypes.shape({
    a: PropTypes.string,
    b: PropTypes.string,
  }).isRequired,
  other: PropTypes.string.isRequired,
}

type Props = PropTypes.InferProps<typeof propTypes>;

const Tester: React.FC<Props> = (props) => <div>{JSON.stringify(props.test)}</div>;

Tester.propTypes = propTypes;

export default Tester;
Related