add React.PropTypes.any
add the ability for React propTypes to accept an `any` type: `someProp: React.PropTypes.any`. This is more useful when combined with `.isRequired`, to enforce that _something_ is passed: `someProp: React.PropTypes.any.isRequired`
Cheng Lou committed
Jan 10, 2014 at 20:17 UTC
d14ce00dc30889e5e9ecf3b28187101510647664
2 files changed
+39
-1
src/core/ReactPropTypes.js
+13
-1
@@ -87,12 +87,24 @@ var Props = {
87
instanceOf: createInstanceTypeChecker,
88
89
renderable: createRenderableTypeChecker(),
90
- component: createComponentTypeChecker()
90
91
+ component: createComponentTypeChecker(),
92
+
93
+ any: createAnyTypeChecker()
94
};
95
96
var ANONYMOUS = '<<anonymous>>';
97
98
+function createAnyTypeChecker() {
99
+ function validateAnyType(
100
+ shouldThrow, propValue, propName, componentName, location
101
+ ) {
102
+ // always is valid
103
+ return true;
104
+ }
105
+ return createChainableTypeChecker(validateAnyType);
106
+}
107
+
108
function isRenderable(propValue) {
109
switch(typeof propValue) {
110
case 'number':
src/core/__tests__/ReactPropTypes-test.js
+26
@@ -347,4 +347,30 @@ describe('Union Types', function() {
347
});
348
});
349
350
+ describe('Any type', function() {
351
+ it('should should accept any value', function() {
352
+ expect(typeCheck(Props.any, 1)).not.toThrow();
353
+ expect(typeCheck(Props.any, 'str')).not.toThrow();
354
+ expect(typeCheck(Props.any.isRequired, 1)).not.toThrow();
355
+ expect(typeCheck(Props.any.isRequired, 'str')).not.toThrow();
356
+
357
+ expect(typeCheck(Props.any, null)).not.toThrow();
358
+ expect(typeCheck(Props.any, undefined)).not.toThrow();
359
+
360
+ expect(typeCheck(Props.any.isRequired, null)).toThrow(
361
+ 'Invariant Violation: Required prop `testProp` was not specified in ' +
362
+ '`testComponent`.'
363
+ );
364
+ expect(typeCheck(Props.any.isRequired, undefined)).toThrow(
365
+ 'Invariant Violation: Required prop `testProp` was not specified in ' +
366
+ '`testComponent`.'
367
+ );
368
+ });
369
+
370
+ it('should have a weak version that returns true/false', function() {
371
+ expect(typeCheck(Props.string.weak, null)()).toEqual(true);
372
+ expect(typeCheck(Props.any.weak.isRequired, null)()).toEqual(false);
373
+ expect(typeCheck(Props.any.isRequired.weak, null)()).toEqual(false);
374
+ });
375
+ });
376
});