milesj / babel-plugin-typescript-to-proptypes

Generate React PropTypes from TypeScript interfaces or type aliases.
MIT License
367 stars 25 forks source link

enums transform to .any #17

Closed mhaidamashko closed 5 years ago

mhaidamashko commented 5 years ago

Thanks for your work! I've found issue with enums. They all transformed to PropTypes.any. I've forked the repo and added a fixture:

import React, { FC } from 'react';

export enum Color {
    Green = 'green',
    Red = 'red',
}

export interface Props {
    color: Color,
}

const TypeAsEnum: FC<Props> = () => {
    return null;
};

export default TypeAsEnum;

and the resulting snapshot is:

exports[`babel-plugin-typescript-to-proptypes transforms ./fixtures/type-as-enum.ts 1`] = `
"import _pt from 'prop-types';
import React, { FC } from 'react';
export enum Color {
  Green = 'green',
  Red = 'red',
}
export interface Props {
  color: Color;
}

const TypeAsEnum: FC<Props> = () => {
  return null;
};

TypeAsEnum.propTypes = TypeAsEnum{
  color: _pt.any.isRequired
};
export default TypeAsEnum;"
`;

Do we have some workaround for this? It would be cool if we have PropTypes.oneOf for this.

milesj commented 5 years ago

@mhaidamashko Whoops, looks like I did forget about enum. At minimum, all you would need to do is add another if block like this one: https://github.com/milesj/babel-plugin-typescript-to-proptypes/blob/master/src/convertBabelToPropTypes.ts#L213

mhaidamashko commented 5 years ago

@milesj Hey, thank you for fast response. I've tried to make it works, but with no results. After research I've found the enum has type TSTypeReference and doesn't has enough information to create right propTypes. console.log(type) is:

 Node {
        type: 'TSTypeReference',
        start: 133,
        end: 138,
        loc:
         SourceLocation {
           start: Position { line: 9, column: 11 },
           end: Position { line: 9, column: 16 } },
        typeName:
         Node {
           type: 'Identifier',
           start: 133,
           end: 138,
           loc:
            SourceLocation { start: [Position], end: [Position], identifierName: 'Color' },
           name: 'Color' } }

Have any ideas?

milesj commented 5 years ago

@mhaidamashko The AST is Babel, which does have a node of TSEnumDeclaration. https://astexplorer.net/#/gist/f11e97f011504123f3b008adb17c0aa4/56a23ecfacb3bb0215fd8505c11c722a6157d49e

milesj commented 5 years ago

Now supports enums and partial support for enum members (full support requires the type checker).