typescriptreact-proptypes

React PropTypes with typescript template literal Types


Typescript 4.1 allowing using Template Literal Types which can be used to simulate simple regex patterns, so I could assert certain types of strings and not any string.

Let's say that I have the following type:

type percentStr = `${number}%`;
type relativeOrAbsStr = number | `${number | percentStr}${number | ''}`;

Can be a number, a number-string followed by % and optionally another number after:

example ok: 33(number),'33%','10%330','500%30'
example error: '23'(string-number not followed by %)

However - PropTypes complain if a try to use PT.string as an option because this type cannot be any string, it should be a string of a certain shape.

import PT from 'prop-types';
type myStr:relativeOrAbsStr = PT.oneOfType([PT.string, PT.number])
// Type 'string' is not assignable to type 'relativeOrAbsStr'.

Currently, as a workaround I use as any assertion:

type myStr:myStr:relativeOrAbsStr = PT.oneOfType([PT.string as any, PT.number]),

How do I define an appropriate prop-types type for my template string literal type?


Solution

  • we can provide custom validator function to check propType:

    const pAnchorString = (props, propName, componentName) => {
      if (!/^\d+%?\d*$/.test(props[propName])) {
        return new Error('Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
      }
    };
    

    this will validate against '10','10%','10%10' but not 's','10s' etc