Giter Site home page Giter Site logo

prop-types's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prop-types's Issues

export `isValidElement`?

Could there be an entry point for isValidElement? I'd like to use it without depending on React :-)

Context around the change

Other than the fact mentioned on the blog We've extracted the built-in prop types to a separate package to reflect the fact that not everybody uses them. is there any other use of moving it to separate module?

Access property type for documentation purposes at run time

Looking at how storybook and random questions on the internet it looks like it would be preferable to be able to pull the type of the property after it has been set.

I have a simple POC I can submit as a PR if that would be preferred. Code below as to what I would be expecting to have as an end result.

// this would be set with the validator
function getType() {
      return {
        type: type,
        subType: subType
      }
    }
propEnum.getType() => {type: "enum", subType: Array(4)}
propString.getType() => {type: "string", subType: undefined}

How to depend on this package?

Hi,
I have a package that has react as a peerDependency and provides PropTypes for the component it exports. Now that the prop-types is a separate package I would like to use it as a peerDependency as well but in an opt-in way (for users that use TypeScript, PropTypes are redundant). Is there a recommended way of handling this situation?

Thanks

Add ability to throw error instead of warning in tests

In tests it would be nice to throw an error if the property isn't of its expected type.

It would be nice if this could be scoped to our own components and not 3rd party ones using 3rd party components, but thats not necesary.

People are already turning console.warning calls to throw errors, so this would be a nice upgrade for them.

PropTypes throwing errors in production?

Currently in React 15.5.0, PropTypes called manually can result in an Error being thrown in production. This is due to the productionTypeChecker now being used in 15.5.0. We suspect that the boolean argument passed to invariant was either intended to be flipped, or warning was intended to be used instead here. Passing false to invariant will always throw an error.

We're currently seeing this occur in production as a result of using react-router v1.0.3, which expects PropType validators to return errors, and doesn't account for any errors being thrown.

Enable CI testing

Currently, there is no CI setup for running the unit tests against PRs. There should be!

Question: should typed arrays be supported?

Hey. In my app I make heavy use of typed arrays. If I recall correctly, PropTypes treats them as objects, and having to say that my components required an object when they only took typed arrays felt like a bug-due-to-bad-documentation waiting to happen. So I made my own validation for it (see below).

However, I was wondering if typed array support shouldn't be part of the main package? I mean, I'm not really requesting it since I already fixed it for myself, and I know that their usage is relatively rare, but on the other hand: they are a core part of the language, so it feels a bit different from making custom validators for your own specific objects.

(And hey, even if you don't want to add it to the main prop-types package, at least the next person to look for typed array support can use something based on the code below)

export const TypedArrayProp = {
  any: (props, propName, componentName) => {
    let obj = props[propName];
    if (!(obj instanceof Float64Array ||
      obj instanceof Float32Array ||
      obj instanceof Int32Array ||
      obj instanceof Int16Array ||
      obj instanceof Int8Array ||
      obj instanceof Uint32Array ||
      obj instanceof Uint16Array ||
      obj instanceof Uint8Array ||
      obj instanceof Uint8ClampedArray)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a typed array.'
      );
    }
  },

  float64: (props, propName, componentName) => {
    if (!(props[propName] instanceof Float64Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Float64Array.'
      );
    }
  },

  float32: (props, propName, componentName) => {
    if (!(props[propName] instanceof Float32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Float32Array.'
      );
    }
  },

  float: (props, propName, componentName) => {
    if (!(props[propName] instanceof Float64Array ||
      props[propName] instanceof Float32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Float32Array or Float64Array.'
      );
    }
  },

  int32: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an Int32Array.'
      );
    }
  },

  int16: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int16Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an In16Array.'
      );
    }
  },

  int8: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int8Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an Int8Array.'
      );
    }
  },

  int: (props, propName, componentName) => {
    if (!(props[propName] instanceof Int32Array ||
      props[propName] instanceof Int16Array ||
      props[propName] instanceof Int8Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected an Int32Array, In16Array, or Int8Array.'
      );
    }
  },

  uint32: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint32Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint32Array.'
      );
    }
  },

  uint16: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint16Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint16Array.'
      );
    }
  },

  uint8: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint8Array)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint8Array.'
      );
    }
  },

  uint8clamped: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint8ClampedArray)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint8ClampedArray.'
      );
    }
  },

  uint: (props, propName, componentName) => {
    if (!(props[propName] instanceof Uint32Array ||
      props[propName] instanceof Uint16Array ||
      props[propName] instanceof Uint8Array ||
      props[propName] instanceof Uint8ClampedArray)) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Expected a Uint32Array, Uint16Array, Uint8Array, or Uint8ClampedArray.'
      );
    }
  },
};

export { TypedArrayProp as default };

Unmet dependency for react 15.2.*

+-- [email protected]
+-- UNMET PEER DEPENDENCY react@^0.14.0 || ^15.0.0
`-- UNMET PEER DEPENDENCY react-dom@^15.4.2

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN [email protected] requires a peer of react-dom@^15.4.2 but none was installed.
npm WARN [email protected] requires a peer of react@^0.14.0 || ^15.0.0 but none was installed.
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.

use PropTypes from custom type function

is there any way to use the PropTypes validator from within custom props

i want to be able to do something like:

export const UnitPropType = (props, propName, componentName) => {
  const val = props[propName];
  const valid =
    PropType.oneOf(myKeys) ||
    PropTypes.instanceof(MediaQueryValue) ||
    PropTypes.arrayOf(MediaQueryValue);


  if (!valid) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
};

importing prop-types into a HOC is `undefined`

I'm creating a higher order component following the example on the React documentation website.

Here's a very simplified version of my HOC. This is in a file by itself.

import React from 'react';
import PropTypes from 'prop-types';

export default function HigherOrderComponent(WrappedComponent) {
  class Wrapper extends React.Component {
    static propTypes = {
      children: PropTypes.oneOfType([
        PropTypes.arrayOf(PropTypes.node),
        PropTypes.node,
      ]).isRequired,
    }

    componentDidMount() {
      // this.doStuff()
    }

    render() {
      return (
        <WrappedComponent
          {...this.props}
          wrapped={'Hey, I am a prop from the HOC!'}
        >{this.props.children}</WrappedComponent>);
    }
  }

  return Wrapper;
}

For some reason, PropTypes is "undefined". However, if I change every instance of PropTypes to React.PropTypes, it works just fine because it is accessing the PropTypes object from React.

It could be something related to babel / rollup, but I'm not sure. But I am suspicious of the issue being in Babel or Rollup because React gets passed through just fine.

Here is my .babelrc file:

{
  "presets": ["es2015-rollup", "react"],
  "plugins": [
    "transform-class-properties"
  ]
}

Checklist:

  • 'prop-types' is listed in my package.json under "dependencies"
  • I deleted my node_modules folder and ran npm i
  • import PropTypes from 'prop-types'; in other files seems to work just fine. I think it has to do with PropTypes being used in a function?

I have a repo with the issue on github if you want to see the full example. PM me if you want to check that out.

Documentation about custom validators calling other validators

Hello,
I am wondering how to implement a custom validator which checks the type of an object.

The documentation is very clear for custom validators which do not call other validators, but it is quite unclear how validators should be called from custom validators. I have tried using PropTypes.checkPropTypes but couldn't make it happen.


Here is a solution that seems to be working:

// const customPropTypes = {...}

function (props, propName, componentName, ...rest) {
  if (props[propName]) {
    const { type } = props[propName]

    if (!type) {
      return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Missing type.`)
    } else if (Object.keys(customPropTypes).indexOf(type) === -1) {
      return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Unhandled type: ${type}.`)
    }

    return customPropTypes[type](props, propName, componentName, ...rest)
  }

  return null
}

Another challenge is to make the custom validator chainable in order to chain it with .isRequired. A blog post suggested to implement it this way:

const ANONYMOUS = '<<anonymous>>'

export default function createChainableTypeChecker (validate) {
  function checkType (isRequired, props, propName, componentName, ...rest) {
    componentName = componentName || ANONYMOUS

    if (props[propName] == null) {
      // var locationName = ReactPropTypeLocationNames[location]
      if (isRequired) {
        // return new Error(`Required ${locationName} \`${propName}\` was not specified in \`${componentName}\`.`)
        return new Error(`Required \`${propName}\` was not specified in \`${componentName}\`.`)
      }
      return null
    } else {
      return validate(props, propName, componentName, ...rest)
    }
  }

  var chainedCheckType = checkType.bind(null, false)
  chainedCheckType.isRequired = checkType.bind(null, true)

  return chainedCheckType
}

I commented out the part related to locationName as I could not figure out where ReactPropTypeLocationNames


Is it the way to solve to implement custom validators which call other validators ?

Does 'prop-types' also check the node_modules?

I've literally searched my whole (own) codebase for every React.PropTypes call and replaced them with the new PropTypes call, but I still get the warning.

Is it possible this is because of a dependency in my node_modules that's still using the React.PropTypes call?

how to check what type does the checker function accept?

I have a react component imported and its .propTypes available, i.e. a map of all prop names to their checker function. Now I would like to get their accepting types.

One way I can think of is to feed each checker function with some value and find out. It should work totally fine for native value. The other is to extend each checker's prototype and record expected type info.

Is there a more proper and present way to do this?

Is there a prop type for stateless functions that return a jsx component?

I wanted to use PropTypes.element to validate that the incoming prop was a component, but it is a stateless function that returns a JSX element. My eslint tells me that a function was supplied, but an element was expected. Is this an eslint issue, or should there be a prop type for a React stateless function?

Build artifacts shouldn't be committed to source control

prop-types.js and prop-types.min.js are build artifacts and thus it doesn't really make sense for them to be committed to source control. Having them in source control makes diffs messier, unnecessarily bloats out the repository, and makes it easy for someone to forget to update them. They should be in the .gitignore.

`npm install prop-types --save` resolves to tarball

I'm not sure if this is normal for npm -- and I can't find much on google?

Issuing the following command:

> npm install prop-types --save
somePackage /Users/user/some-package
└── [email protected]

resolves in:

"prop-types": "https://registry.npmjs.org/prop-types/-/prop-types-15.5.8.tgz",

Issuing the following command

> npm install prop-types@latest --save
somePackage /Users/user/some-package
└── [email protected]  invalid

resolves in:

"prop-types": "^15.5.8",

This is not the case for all other packages. Just wanted to give a heads up in case it's something about the packaging of this module.

Cannot find module "fbjs/lib/emptyFunction"

Uncaught Error: Cannot find module "fbjs/lib/emptyFunction"

factoryWithTypeCheckers.js?dcd5:12

.//prop-types//fbjs/lib/emptyFunction.js

Module build failed: Error: ENOENT: no such file or directory, open 'node_modules\prop-types\node_modules\fbjs\lib\emptyFunction.js'

.//prop-types//fbjs/lib/invariant.js

Module build failed: Error: ENOENT: no such file or directory, open 'node_modules\prop-types\node_modules\fbjs\lib\invariant.js'

.//prop-types//fbjs/lib/warning.js

Module build failed: Error: ENOENT: no such file or directory, open 'node_modules\prop-types\node_modules\fbjs\lib\warning.js

process.env.NODE_ENV get replaced by 'development' in umd

The process.env.NODE_ENV gets replaced by 'development' in umd

In file prop-types/factoryWithTypeCheckers.js: (line 148)

  function createChainableTypeChecker(validate) {
    if (process.env.NODE_ENV !== 'production') {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }

In umd bundle prop-types.js:

  function createChainableTypeChecker(validate) {
    if ("development" !== 'production') {
      var manualPropTypeCallCache = {};
      var manualPropTypeWarningCount = 0;
    }

making the condition always true, is it by design or a bug?

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

I keep getting warning errors when running my jest tests after updating to prop-types package:

PASS  __tests__/pages/about.test.js
  ● Console

    console.error node_modules/fbjs/lib/warning.js:36
      Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

package.json:

"dependencies": {
    "babel-eslint": "^7.2.1",
    "contentful": "^4.1.2",
    "csso": "^3.0.1",
    "element-class": "^0.2.2",
    "es6-promise": "^4.1.0",
    "eslint": "^3.18.0",
    "eslint-config-airbnb": "^14.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.10.3",
    "isomorphic-fetch": "^2.2.1",
    "lodash.camelcase": "^4.3.0",
    "lodash.merge": "^4.6.0",
    "memory-cache": "^0.1.6",
    "next": "^2.1.1",
    "randomstring": "^1.1.5"
  },
  "devDependencies": {
    "babel-jest ": "^19.0.0",
    "babel-plugin-transform-define": "^1.2.0",
    "babel-preset-es2015": "^6.24.0",
    "bunyan": "^1.8.10",
    "enzyme": "^2.8.0",
    "jest": "^19.0.2",
    "jest-cli": "^19.0.2",
    "lighthouse": "^1.6.3",
    "prop-types": "^15.5.6",
    "react": "^15.4.2",
    "react-addons-test-utils": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-markdown": "^2.4.6",
    "react-test-renderer": "^15.4.2",
    "sinon": "^2.1.0"
  },

About.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

Tried upgrading "react", "react-addons-test-utils", "react-dom" and "react-test-renderer" to 15.5.1 - Didn't work
Tried upgrading "react", "react-addons-test-utils", "react-dom" to 15.5.3 - Didn't work

Any help would be appreciated. Thanks

Intersection types

I'm working on some tools related to moving back and forth between prop-types and Flow types.

One major omission is intersection types because there's no way to represent them in prop-types.

So I was thinking of a new validator eachOf which could be used for this:

let validator = PropTypes.eachOf([
  PropTypes.shape({ foo: PropTypes.number }),
  PropTypes.shape({ bar: PropTypes.number })
]);

test(validator, { foo: 1 }); // Error: Missing `bar`
test(validator, { bar: 2 }); // Error: Missing `foo`
test(validator, { foo: 1, bar: 2 }); // Works!

It'd work similar to PropTypes.oneOf except it's arr.every() instead of arr.some().

Specify Valid Children Component Types

I was expecting to be able to use PropTypes.instanceOfto specify valid children types, like so:

    static propTypes = {
        children: PropTypes.arrayOf(PropTypes.oneOfType([ 
          PropTypes.instanceOf(ComponentOne), 
          PropTypes.instanceOf(ComponentTwo)
        ]))
    }

I got a relatively obscure error: Failed prop type: Right-hand side of 'instanceof' is not an object

After some searching, stumbled on: facebook/react#2979

The explanation/reason for closing being that instanceOf doesn't work on components. Okay, so would still like to achieve the end goal somehow. facebook/react#2979 (comment) is actually pretty slick.

Just specifying PropTypes.element is not sufficient, IMO.

I'm assuming this is a feature request, but maybe I'm overlooking something. TIA.

Object propType in oneOfType

Hi,
I get some weird issue with propTypes like this:

DateValidator.propTypes = {
    value: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.string,
        PropTypes.number,
    ]),
};

It gives me error:

Warning: Failed prop type: Invalid prop `value` supplied to `DateValidator`.

So useful :)

After some debug I see

PropTypeError {message: "Invalid prop `value` of type `date` supplied to `DateValidator`, expected `boolean`.", stack: ""}
PropTypeError {message: "Invalid prop `value` of type `date` supplied to `DateValidator`, expected `string`.", stack: ""}
PropTypeError {message: "Invalid prop `value` of type `date` supplied to `DateValidator`, expected `number`.", stack: ""}

So after some magic object is transformed to boolean. Why this can happen?

You can check it in my package

react: 15.5.4
prop-types: 15.5.8

Update:
As I see, the problem only with value prop, if I rename it, all works fine. But why this happening? Why something replace object with bool?

Using plain "PropTypes.bool" results in "warning.js:36 Warning: Failed prop type:"

Here is the snippet that gives me the error:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

import SmartField from './SmartField'

export default class MyComponent extends Component {
  static propTypes = {
    title: PropTypes.string,
    parameters: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    isStatic: PropTypes.bool,
    hidden: PropTypes.bool
  }

  render() {
    ...
  }
}

Makes no sense in my book that this is the only instance in my whole project where PropTypes.bool refuses to work

Warning: Failed prop type: MyComponent: prop type isStatic is invalid; it must be a function, usually from React.PropTypes.

Why PropType.boolean is function

Modal.propTypes = {visible: PropTypes.boolean}

Warning: Failed prop type: Modal: prop type visible is invalid; it must be a function, usually from React.PropTypes.

I think that the boolean type should be called 'boolean'
You can add boolean as alias for bool, for expected behavior PropTypes

I think if undefined PropType shouldn't be function

Using prop-types outside of React

Now that prop-types is a top-level package, it occurs to me that there are several use cases where this could be a useful library outside of React.

Use Case

Suppose, for example, you are writing an application with a REST interface that takes in some complicated JSON data, and queries MongoDB:

app.post("/api/getLastUserLogin", (req, res) => {
    // Expect req.body to be a `{username}` object.
    db.users.find({username: body.username})
    .then(users => {
        res.json(users[0] && users[0].lastLoginTime);
    });
});

Simple enough... But, oh noes! There are dark forces at work on the internet, and someone sends us this JSON body:

{"username": {"$ne": ""}}

MongoDB faithfully tries to load all 10 million of our users into memory, the server crashes, our company goes bankrupt, and our children starve.

But wait! prop-types to the rescue!

const LastUserLoginMessageType = {
    username: PropTypes.string.isRequired
}

app.post("/api/getLastUserLogin", (req, res) => {
    if(!PropTypes.validate(LastUserLoginMessageType, req.body)) {
        return res.status(400).send("Not today, hax0r!");
    }
    ...
});

Why this is awesome

There's a lot to recommend this. First, it's easy to check types without having to pull in some extra build step like TypeScript or Flow (especially nice on existing projects which don't already incorporate those technologies). Second, it's a syntax that many people are already very familiar with, because it's so widely used in React.

The challenge is, of course, that today prop-types is so tightly coupled to React. For starters, all of prop-types is disabled if NODE_ENV === 'production', which is an obvious problem, so there'd need to be some changes. Turning prop-types into a more general-purpose library should have advantages for React though, as it should make it easier to do things like #28.

API Proposal

This is just to give a vague idea of what I'm after here, there's lots of room for improvement on this, but:

PropTypes.isInvalid(typeSpec, value, options)

  • typeSpec is an object where keys are property names, and values are the associated PropType objects (e.g. {username: PropTypes.string}).
  • value is the object we're going to check.
  • options.context - See options.onValidationError().
  • options.onValidationError({path, expectedType, actualType, errorString, context}) - If this function returns a truthy value, then isInvalid() will return that value immediately. If this function throws, the the error will propagate all the way to the caller of isInvalid(). path is the path of the value being checked (e.g. "user.name"). expectedType is the type that was expected at this path (e.g. 'string'), actualType is the type we actually found. context is the options.context object passed to isInvalid(). errorString is an english-language ready made error string to describe what went wrong. The default implementation simply returns errorString.

I think this gives you flexibility to do quite a bit. The existing React use case, where we need to know if value came from props or context or whatever is solved by passing {location, componentName} along in the context, so onValidationError() can construct an appropriate string. React would set onValidationError: () => null when running production code.

One minor downside to this is it makes a webpacked production React app slightly bigger, since all this code that used to get optimized out is no longer going to be enclosed in NODE_ENV === 'production' checks. I can think of a couple of ways around that, but I'll leave that for future discussion.

Set defaultProps together with propTypes

Maybe this already exists, but right now I have to set defaultProps on my propTypes as a separate definition:

import PropTypes from 'prop-types';

...

MyComponent.propTypes = {
  propA: PropTypes.func,
  propB: PropTypes.bool.isRequired,
  propC: PropTypes.string
};

MyComponent.defaultProps = {
  propA: () => {},
  propC: 'Default String'
};

This can be really annoying for long lists of props. Not sure how this matches up with react philosophy, but it would be good to have a way to set types and defaults in one go to reduce code repetition and reduce opportunities for bugs:

PropTypes.setPropTypes(MyComponent, {
  propA: { type: PropTypes.func, default: () => {} },
  propB: PropTypes.bool.isRequired,
  propC: { type: PropTypes.string, default: 'Default String' }
})

errors after flow check

Hi all,
this issue are struggling me.

After a flow check there are these errors and i don0t know how to fix:

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:11
11: declare var array: React$PropType$Primitive<Array>;

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:18
18: declare var arrayOf: React$PropType$ArrayOf;
^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$ArrayOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:20
20: declare var instanceOf: React$PropType$InstanceOf;
^^^^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$InstanceOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:22
22: declare var objectOf: React$PropType$ObjectOf;
^^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$ObjectOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:23
23: declare var oneOf: React$PropType$OneOf;
^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$OneOf. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:24
24: declare var oneOfType: React$PropType$OneOfType;
^^^^^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$OneOfType. Could not resolve name

Library type error:
flow-typed/npm/prop-types_v15.x.x.js:25
25: declare var shape: React$PropType$Shape;
^^^^^^^^^^^^^^^^^^^^ identifier React$PropType$Shape. Could not resolve name

prop-types doesn't validate props when using decorators

Not sure is it a problem with babel decorators transpiling or with prop-types (or something else) but when I use decorators I don't get errors in console about types mismatch. Code below won't raise any errors about 'fetchPaymentStatus' not being a string:

zrzut ekranu 2017-06-09 o 14 02 52

It will however raise error about not supplying required attribute.

If this is required I can prepare some test repo.

disallow null

When a type is optional it allows undefined or null. Unfortuantly prop-types eats the null and doesn't run any validators, so there doesn't seem to be a way to create a custom validator to disallow nulls.

Optimize defaultProps with propTypes

Do you want to request a feature or report a bug?
feature,
PropTypes.string('default string');
What is the current behavior?
Two statics representing the same thing is kind of Trivial.

Component.propTypes = {
  foo: T.string,
  bar: T.number.isRequired,
};
Component.defaultProps = {
  foo: '12',
}

Sometimes people write useless code with this design. And you can't tell what is the author wanted.

Component.propTypes = {
  foo: T.string,
  bar: T.number.isRequired, // unnecessary isRequired.
};
Component.defaultProps = {
  foo: '12',
  bar: 12, // or unnecessary defaultProp.
}

What is the expected behavior?
Make defaultProps work with propTypes. One static other than two statics will be much easier for HOC and Developers to customize, modify or remove.

Component.propTypes = {
  foo: T.string('12'),
  bar: T.number.isRequired,
  // or
  foo: T.string.default('12'),
};

Why react should be declared as peerDependencies and prop-type as dependency ?

Hi Team, I've a question regarding the suggestion made in the readme on how to depend on prop-type:

https://github.com/reactjs/prop-types#how-to-depend-on-this-package

As a library maintainer both react and prop-type should be considered as external dependencies to my libraries as they should come from the environement using them and they should not be merged . So far I always thought that the peerDependency was the correct way of listing those dependencies (react and react-dom so far).
Now I'm a bit confused because you are suggesting to use prop-type as dependencies and not peerDependencies, what makes prop-types different to react ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.