Zan
Zan is a drop in replacement for React.PropTypes
:
;React;
The primary differences between Zan and React.PropTypes
are:
- Checks are
isRequired
by default and expose anisOptional
property - Provides an
exactShape
type checker - Provides introspection methods
- Provides methods to help you create your own type checkers
API
zan.types
Exposes all the same type-checkers as React.PropTypes
. Each type-checker is required by default and has the following properties:
-
isOptional
- Returns an optional type checker. Optional checkers behave likeReact.PropType
's default behavior. -
inspectArgs()
- Returns the arguments passed to the type-checker creator.Example:
shape(o).inspectArgs() === o
-
inspectType()
- Returns the checker type.Example:
shape(o).inspectType() === shape
. -
inspectIsOptional()
- Return whether or not the checker is optionalExample:
shape(o).inspectIsOptional() === false
.Example:
shape(o).isOptional.inspectIsOptional() === true
.
zan.types.exactShape(shape)
Like shape()
, but disallows unrecognized keys.
zan.check(type, value, [label])
Validates value against a type checker. Useful when using Zan outside of React components. Returns null
if the data validates successfully or an Error
object if there's an error:
Error: Invalid prop `value.field[0].subField` of type `object` supplied to `label`, expected an array.
Usage:
// Normalconst error = zan;// Curriedconst check = zan;const error = ;
createCustomChecker(checkerFn)
Allows you to create your own type checker. Here's how you'd create a checker
that validates that data is an instance of a RegExp
:
const regex = zan;// regex gets all of Zan's built-in goodness:regexisOptional;regex === regex;
The checker is passed all the same arguments as React PropType checkers: props
, propName
, componentName
, location
, and propFullName
.
A Note on Error Formats
The final checker errors will be in one of two forms:
Required prop `field.subField[0].name` was not specified in `MyComponent`.
Invalid prop `field.subField[0].name` of (type `number` OR value `xyz`) supplied to `MyComponent`...
If you return an error that doesn't start with Required
or Invalid
then Zan prefixes the error message with:
Invalid prop `field.subField[0].name` of value `xyz` supplied to `MyComponent`:
createCustomCheckerCreator(checkerCreatorFn)
This is like createCustomChecker()
but is for checkers that require arguments:
const range = zan;// regex gets all of Zan's build-in goodness:isOptional; === range;
recursive(types)
Converts native arrays and objects to arrayOf()
and shape()
calls, so you don't have to:
;const number string = types; const propTypes = ; // ...is equivalent to: const propTypes = myAge: number myFavoriteNumbers: treeNode: buddies: ;
see test.js from more usage