Search code examples
reactjstypescriptreact-proptypes

React, typescript and prop-types: how to use own type?


I have a string type literal, something in the form of type MyType = 'str1' | 'str2' | 'str3' and I want one of my props to accept only this type, but I have no idea how to tell PropTypes.

I've tried to use propTypes.oneOf(['str1', 'str2', 'str3']) but then typescript infer it as a normal string, which I don't want.


Solution

  • Since this is type checking with TypeScript, you don't try to do it at the React runtime level (propTypes), you do it at the TypeScript level.

    Your component should use your string literal type in its props type:

    type MyComponentProps = {
        propName: MyType;
    }
    

    Then if its a class component:

    class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
        // ...
    }
    

    Or if you're using a functional component:

    const MyComponent: React.FC<MyComponentProps> = ({propName}) => {
        // ...
    };