From 539222261baa1120c20a3f4ed020ecbd60a1f01b Mon Sep 17 00:00:00 2001 From: Chandler Prall Date: Tue, 11 Dec 2018 12:21:56 -0700 Subject: [PATCH] Support null & undefined as proptype literals --- .../babel/proptypes-from-ts-props/index.js | 18 +++++++++++---- .../proptypes-from-ts-props/index.test.js | 23 +++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/scripts/babel/proptypes-from-ts-props/index.js b/scripts/babel/proptypes-from-ts-props/index.js index 25387ae3926f..12b3144bf4ff 100644 --- a/scripts/babel/proptypes-from-ts-props/index.js +++ b/scripts/babel/proptypes-from-ts-props/index.js @@ -355,7 +355,7 @@ function getPropTypesForNode(node, optional, state) { const reducedUnionTypes = tsUnionTypes.reduce( (foundTypes, tsUnionType) => { - if (types.isLiteral(tsUnionType)) { + if (types.isLiteral(tsUnionType) || (types.isIdentifier(tsUnionType) && tsUnionType.name === 'undefined')) { if (foundTypes.oneOfPropType == null) { foundTypes.oneOfPropType = types.arrayExpression([]); foundTypes.unionTypes.push( @@ -511,10 +511,20 @@ function getPropTypesForNode(node, optional, state) { optional = true; // cannot call `.isRequired` on a boolean literal break; + case 'TSNullKeyword': + propType = types.nullLiteral(); + optional = true; // cannot call `.isRequired` on a boolean literal + break; + + case 'TSUndefinedKeyword': + propType = types.identifier('undefined'); + optional = true; // cannot call `.isRequired` on a boolean literal + break; + // very helpful debugging code - // default: - // debugger; - // throw new Error(`Could not generate prop types for node type ${node.type}`); + default: + debugger; + throw new Error(`Could not generate prop types for node type ${node.type}`); } // if the node was unable to be translated to a prop type, fallback to PropTypes.any diff --git a/scripts/babel/proptypes-from-ts-props/index.test.js b/scripts/babel/proptypes-from-ts-props/index.test.js index 88a6f0473f9f..b7ae6d2f108a 100644 --- a/scripts/babel/proptypes-from-ts-props/index.test.js +++ b/scripts/babel/proptypes-from-ts-props/index.test.js @@ -977,6 +977,29 @@ FooComponent.propTypes = { };`); }); + it('treats null and undefined as literals', () => { + const result = transform( + ` +import React from 'react'; +interface IFooProps {bar: 'five' | null | undefined} +const FooComponent: React.SFC = () => { + return (
Hello World
); +}`, + babelOptions + ); + + expect(result.code).toBe(`import React from 'react'; +import PropTypes from "prop-types"; + +const FooComponent = () => { + return
Hello World
; +}; + +FooComponent.propTypes = { + bar: PropTypes.oneOf(["five", null, undefined]).isRequired +};`); + }); + }); describe('array / arrayOf propTypes', () => {