Generating PropTypes from TypeScript Components
This post is part of a series sharing issues and adventures building a component library and documentation from scratch.
One common thing to want when documenting your React code is to show available prop types. The most well-known tool for generating this data is react-docgen
. However, if you are using TypeScript, react-docgen
is not an option as it only support babylon
(and by extention Flow Type). Any reasonable developer would immediatly google for "react-docgen typescript" and find react-docgen-typescript
.
react-docgen-typescript
Browsing other component libraries I saw examples showing not only which props could be used for each component, but the heigherarchy as well. The parse
method of react-docgen
provides lots of good info about a component including the composes
key to see prop relationships. Sadly, I was wrong to assume that react-docgen-typescript
provides the same info.
Here's a contrived example of a simple Button component:
interface IButton {
onClick: () => void;
}
interface IProps extends IButton {
color: string;
bg: string;
}
class Button extends Component<IProps> { ... }
The output of react-docgen-typescript
flattens the prop type hierarchy and does not retain any information about the extending of other interfaces. This limits the documentation I'd like to be able to show. I spent several hours searching in vain for alternatives to react-docgen-typescript
.
documentalist
I remembered that BlueprintJS is written in TypeScript and their documenation has awesome prop type information. I looked at what they are doing to generate their prop types (since they couldn't be using react-docgen-typescript
) and discovered documentalist
! Not only did this generate so much more information about my components, it was so easy to use. I copied and pasted the code snippet from their docs and it worked the first time.
documentalist
does export to a separate .json
file, which will need to be generated as part of the build process instead of loaded via webpack, but it seemed like a fair trade-off for the amount of info I was getting. One thing to note is that I ran this on a small set of components and I don't know how long it takes to run on much larger component library.
I can't believe that this tool is not more mainstream considering how involved Palantir is with TypeScript open source (they maintain TSLint). My goal is to put Documentalist out there is a viable alternative to documenting TypeScript components.