Skip to content

Instantly share code, notes, and snippets.

@RyanCCollins
Last active September 14, 2017 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanCCollins/7ca4062a270514d8d2080633a066e60b to your computer and use it in GitHub Desktop.
Save RyanCCollins/7ca4062a270514d8d2080633a066e60b to your computer and use it in GitHub Desktop.
Translate react-desc types to typescript definitions
// Start of a utility for translating react-desc types to TypeScript definitions
// https://www.webpackbin.com/bins/-Ktxj9FtGKCYnA9o_C1_
import * as fp from 'lodash/fp';
const PropTypes = {
string: 'string',
func: 'Function',
oneOf: x => x.join('" | "'),
shape: x => JSON.stringify(x),
oneOfType: x => x.join(' | '),
arrayOf: x => x,
node: 'JSX.Element',
any: 'any',
bool: 'boolean'
}
const schema = {
description: 'A text input field with optional suggestions.',
usage: `import { TextInput } from 'grommet';
<TextInput id='item' name='item' />`,
props: {
defaultValue: [
PropTypes.string, 'What text to start with in the input.',
],
id: [
PropTypes.string, 'The id attribute of the input.',
],
name: [
PropTypes.string, 'The name attribute of the input.',
],
onInput: [
PropTypes.func,
'Function that will be called when the user types in the input.',
],
onSelect: [
PropTypes.func,
`Function that will be called when the user selects a suggestion.
The suggestion contains the object chosen from the supplied suggestions.`,
],
placeholder: [
PropTypes.string, 'Placeholder text to use when the input is empty.',
],
plain: [
PropTypes.bool,
`Whether this is a plain input with no border or padding.
Only use this when the containing context provides sufficient affordance`,
],
size: [
PropTypes.oneOf(['small', 'medium', 'large', 'xlarge']),
'The size of the TextInput.',
],
suggestions: [
PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape({
label: PropTypes.node,
value: PropTypes.any,
}),
PropTypes.string,
])
),
`Suggestions to show. It is recommended to avoid showing too many
suggestions and instead rely on the user to type more.`,
],
value: [
PropTypes.string, 'What text to put in the input.',
],
},
};
const parse = () => fp.compose(
fp.join('"; \n'),
fp.map(fp.join(': "')),
fp.flatten,
fp.map(fp.toPairs),
fp.map(x => ({
[x]: fp.compose(fp.head, fp.get(`props.${x}`))(schema)
})),
fp.keys,
fp.get('props')
)(schema)
console.log(parse())
/*
// Result:
defaultValue: "string";
id: "string";
name: "string";
onInput: "Function";
onSelect: "Function";
placeholder: "string";
plain: "boolean";
size: "small" | "medium" | "large" | "xlarge";
suggestions: "{"label":"JSX.Element","value":"any"} | string";
value: "string";
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment