Force ReactJS to throw real errors when propTypes validation fails? Force ReactJS to throw real errors when propTypes validation fails? javascript javascript

Force ReactJS to throw real errors when propTypes validation fails?


From this answer, you can check the error message against typical react messages and only throw for those. Not perfect, but maybe a step closer to what you're looking for:

let warn = console.warn;console.warn = function(warning) {  if (/(Invalid prop|Failed propType)/.test(warning)) {    throw new Error(warning);  }  warn.apply(console, arguments);};


FlowType, introduced by Facebook yesterday sounds like exactly what you're after. It can analyse your code, infer types, and throw errors at compile time.

It specifically includes support for React and the propTypes argument: https://flow.org/en/docs/react/components/

Update (July 21) - Link above fixed, but given Facebook's recent change on Flow to heavily prioritise internal use over future community use, would recommend TypeScript instead for new projects. Example:

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/class_components/


React 17 - throw in test

beforeEach(() => {  const { error } = console;  jest.spyOn(console, 'error').mockImplementation((...args) => {    const message = args[0].replace('%s%s', '').replace('%s', args[1]) + args[2];    if (/(Invalid prop|Failed prop type)/.test(message)) {      throw new Error(message);    }    error.apply(console, args);  });});