Is it possible to use a React context without PropTypes?

The project I'm working on has recently been ported to TypeScript, which makes React PropTypes redundant, unless indicated contextTypes. Now we are in the process of switching to the React version from 15.5, where PropTypes were moved to a separate package than react. Since our use of PropTypes is so limited, it seems unnecessary to add a dependency prop-typesif there is a way to use the React context without them?

+4
source share
1 answer

It’s just that the presence of a key in an object contextTypesseems wonderful (it is assumed that it uses it hasOwnPropertyunder the hood), but in order not to register any errors, the function returning nullseems necessary. This works both for contextTypesand for childContextTypes.

static contextTypes = {
  router: () => null
};

static childContextTypes = {
  location: () => null
};

getChildContext() {
  return { location: this.props.location };
}

In some cases, TypeScript complains that it () => nulldoes not have a property isRequired. I solved this by creating a helper function fakePropType:

const fakePropType: any = () => null
fakeProptype.isRequired = () => null
+3
source

Source: https://habr.com/ru/post/1684808/


All Articles