PropType for function argument type checking.
See original GitHub issueI’d really like to be able to define the type of arguments a prop function should be called with.
class Test extends Component {
static propTypes = {
foo: PropTypes.func(PropTypes.number).isRequired,
}
...
}
I think that this is the last missing piece we need to really define a React component interface. I might not be the only one to feel the need to comment those signatures. But having a way to do it programmatically would be much better.
class Test extends Component {
static propTypes = {
foo: PropTypes.func.isRequired, //signature: (id: Number)
}
...
}
First attempt
I tried to create a new PropTypes able to do that by wrapping the function given as prop:
function createFuncTypeChecker(...argumentsTypeCheckers) {
function validate(props, propName, descriptiveName, location) {
const propValue = props[propName];
const propType = typeof propValue;
if (propType !== 'function') {
const locationName = location;
return new Error(
`Invalid ${locationName} \`${propName}\` of type \`${propType}\`
supplied to \`${descriptiveName}\`, expected a function.`
);
}
props[propName] = (...args) => {
argumentsTypeCheckers.forEach((typeChecker, i) => {
const error = typeChecker(args, i, `${descriptiveName} arguments`, location);
if (error instanceof Error) {
handleArgumentsTypeError(error);
}
});
propValue.apply(this, args);
};
return null;
}
return createChainableTypeChecker(validate);
}
It’s working but I’m receiving the pretty straightforward warning message:
Warning: Don't set .props.foo of the React component. Instead, specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.
.
Yeh, mutating the prop is not a nice way but that’s the only way I found without modifying React core.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:10
- Comments:8 (1 by maintainers)
+1
I don’t see why you wouldn’t have PropTypes when also using TypeScript. Those PropTypes will validate at runtime while TypeScript will just do it when compiling. For me, they seem to do very different things.
I know this was closed years ago, but I still find this a really useful request. I think I’d be useful to give it a second thought at this whole idea.