-
Notifications
You must be signed in to change notification settings - Fork 353
.set and .setOf (and .map and .mapOf) #190
Description
In a project I'm currently working on, I pass Sets to components.
As a fanatic user of prop-types
to make components easier to reuse/rearrange, I write PropTypes.arrayOf(PopTypes.string.isRequired)
quite often. However, there is currently no counterpart for sets. One resorts to defining a prop PropTypes.object
. This alternative doesn't have quite the positive effect on readability as .arrayOf
.
I would like to discuss adding .set
and especially .setOf
.
I wrote a proof-of-concept. I am also more than happy to provide a pull request including everything from implementation to tests, but figured the wise thing to do is ask for some early feedback.
function createSetOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside setOf.');
}
var propValue = props[propName];
if (!(propValue instanceof Set)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a set.'));
}
var insideValidateResult = null;
var insideValidateContainer = {};
propValue.forEach(function checkValue(value) {
if (null !== insideValidateResult) {
return;
}
insideValidateContainer.value = value;
var error = typeChecker(insideValidateContainer, 'value', componentName, 'value', 'inside ' + propFullName, ReactPropTypesSecret);
if (error instanceof Error) {
insideValidateResult = error;
}
});
return insideValidateResult;
}
return createChainableTypeChecker(validate);
}
Errors in this implementation, unfortunately, look like this: Invalid value `inside highlightedIds` of type `string` supplied to `NameList`, expected `number`.
As values inside a set are not a direct property of the set, it is more difficult to name it in the error message. If the fifth value in an array has the wrong type, the error will blab out that it's array[4]
. In a set, I guess the best thing we could do is say that it's inside set
.
Has this been discussed before?