Skip to content

Commit

Permalink
add React.PropTypes.any
Browse files Browse the repository at this point in the history
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`
  • Loading branch information
Cheng Lou authored and zpao committed Jan 11, 2014
1 parent d8a8f6a commit d14ce00
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/core/ReactPropTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,24 @@ var Props = {
instanceOf: createInstanceTypeChecker,

renderable: createRenderableTypeChecker(),
component: createComponentTypeChecker()

component: createComponentTypeChecker(),

any: createAnyTypeChecker()
};

var ANONYMOUS = '<<anonymous>>';

function createAnyTypeChecker() {
function validateAnyType(
shouldThrow, propValue, propName, componentName, location
) {
// always is valid
return true;
}
return createChainableTypeChecker(validateAnyType);
}

function isRenderable(propValue) {
switch(typeof propValue) {
case 'number':
Expand Down
26 changes: 26 additions & 0 deletions src/core/__tests__/ReactPropTypes-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -347,4 +347,30 @@ describe('Union Types', function() {
});
});

describe('Any type', function() {
it('should should accept any value', function() {
expect(typeCheck(Props.any, 1)).not.toThrow();
expect(typeCheck(Props.any, 'str')).not.toThrow();
expect(typeCheck(Props.any.isRequired, 1)).not.toThrow();
expect(typeCheck(Props.any.isRequired, 'str')).not.toThrow();

expect(typeCheck(Props.any, null)).not.toThrow();
expect(typeCheck(Props.any, undefined)).not.toThrow();

expect(typeCheck(Props.any.isRequired, null)).toThrow(
'Invariant Violation: Required prop `testProp` was not specified in ' +
'`testComponent`.'
);
expect(typeCheck(Props.any.isRequired, undefined)).toThrow(
'Invariant Violation: Required prop `testProp` was not specified in ' +
'`testComponent`.'
);
});

it('should have a weak version that returns true/false', function() {
expect(typeCheck(Props.string.weak, null)()).toEqual(true);

This comment has been minimized.

Copy link
@Twisol

Twisol Jan 11, 2014

Should this read Props.any.weak instead of Props.string.weak?

This comment has been minimized.

Copy link
@chenglou

chenglou Jan 11, 2014

Contributor

crap... will fix, thanks

expect(typeCheck(Props.any.weak.isRequired, null)()).toEqual(false);
expect(typeCheck(Props.any.isRequired.weak, null)()).toEqual(false);
});
});
});

0 comments on commit d14ce00

Please sign in to comment.