react-moment-proptypes icon indicating copy to clipboard operation
react-moment-proptypes copied to clipboard

Adjust type definitions for Validator and RequireableValidator.

Open EskiMojo14 opened this issue 3 years ago • 3 comments

Currently, any validator will use the type T | null | undefined, even if isRequired is used. (as covered in #51)

The way I encountered this issue was using the WeakValidationMap<P> type from React to ensure that all validators are the correct type.

import { WeakValidationMap } from 'react';

export type ComponentWithPropTypes<P> = {
  (props: P): JSX.Element | null;
  propTypes: WeakValidationMap<P>;
};

// somewhere else

import moment from "moment";
import propTypes from 'prop-types';
import momentPropTypes from 'react-moment-proptypes';
import { ComponentWithPropTypes } from "<path>"

type ComponentProps = {
  text: string;
  otherText?: string;
  moreText?: string;
  count: number;
  date: moment.Moment;
  date2?: moment.Moment;
}

const Component: ComponentWithPropTypes<ComponentProps> = (props) => // ...

Component.propTypes = {
  text: propTypes.string.isRequired, // fine
  otherText: propTypes.string, // fine
  otherText: propTypes.number, // error (good, it's checking the wrong type)
  count: propTypes.number, // error (good, it's required but not marked as such)
  date: momentPropTypes.momentObj.isRequired, // error (should be required, but the type is still `T | null | undefined`)
  date2: momentPropTypes.momentObj // fine
}

This PR changes the definitions to fix that, and brings the definitions in line with those from prop-types.

I also added withPredicate to the RequireableValidator, which should fix the issue that #52 aimed to solve.

Let me know if anything needs changing 😄

EskiMojo14 avatar Nov 25 '21 16:11 EskiMojo14

Coverage Status

Coverage remained the same at 100.0% when pulling 54a1f28f229572507d8756bc96c58b1c19ad5458 on actual-experience:master into 89a61c17250ea7b71d55d2855f6739ae4071529a on CalebMorris:master.

coveralls avatar Nov 25 '21 16:11 coveralls

Coverage Status

Coverage remained the same at 100.0% when pulling 54a1f28f229572507d8756bc96c58b1c19ad5458 on actual-experience:master into 89a61c17250ea7b71d55d2855f6739ae4071529a on CalebMorris:master.

coveralls avatar Nov 25 '21 16:11 coveralls

Coverage Status

Coverage remained the same at 100.0% when pulling 54a1f28f229572507d8756bc96c58b1c19ad5458 on actual-experience:master into 89a61c17250ea7b71d55d2855f6739ae4071529a on CalebMorris:master.

coveralls avatar Nov 25 '21 16:11 coveralls