Skip to content
This repository has been archived by the owner on Nov 27, 2023. It is now read-only.

Commit

Permalink
feat: add partial support for onOf propType (#218)
Browse files Browse the repository at this point in the history
  • Loading branch information
KnisterPeter committed Nov 4, 2016
1 parent c2a2542 commit d6d7d1e
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Create typescript definitions files (d.ts) from react components.
* ES6 and ES7 class syntax
* Most PropTypes
* any, array, bool, func, number, object, string, node, element, oneOfType, arrayOf, symbol
* Partial support for oneOf PropType
* required PropTypes
* instanceOf PropTypes (when using API and giving a resolve function)
* jsdoc
Expand Down
14 changes: 14 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export function get(astq: astqts.ASTQ, propertyAst: any, propTypesName: string|u
case 'arrayOf':
const typeDecl = get(astq, typeAst.arguments[0], propTypesName);
return getTypeDeclaration(dom.create.array(typeDecl.type), !required);
case 'oneOf':
// FIXME: This should better be a real enum
const enumEntries = getEnumValues(typeAst.arguments[0].elements);
return getTypeDeclaration(dom.create.union(enumEntries as dom.Type[]), !required);
}

return {
Expand Down Expand Up @@ -95,3 +99,13 @@ function getComplexTypeName(astq: astqts.ASTQ, propertyAst: any,
}
return [required, undefined, typeAst];
}

function getEnumValues(oneOfTypes: any[]): any[] {
return oneOfTypes.map((element: any) => {
// FIXME: This are not named references!
if (element.type === 'StringLiteral') {
return dom.create.namedTypeReference(`'${element.value}'`);
}
return dom.create.namedTypeReference(element.value);
});
}
1 change: 1 addition & 0 deletions tests/es6-class.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ declare module 'component' {
optionalNode?: React.ReactNode;
optionalElement?: React.ReactElement<any>;
optionalMessage?: typeof Message;
optionalEnum?: 'News' | 'Photos' | 1 | 2;
optionalUnion?: string | number;
optionalArrayOf?: number[];
requiredFunc: (...args: any[])=>any;
Expand Down
2 changes: 1 addition & 1 deletion tests/es6-class.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Component.propTypes = {
optionalNode: React.PropTypes.node,
optionalElement: React.PropTypes.element,
optionalMessage: React.PropTypes.instanceOf(Message),
//optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
optionalEnum: React.PropTypes.oneOf(['News', 'Photos', 1, 2]),
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
Expand Down

0 comments on commit d6d7d1e

Please sign in to comment.