0.0.4 • Published 4 years ago

interfaces-to-proptypes v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

interfaces-to-proptypes

A library for generically exporting TypeScript interfaces in TS files and converting them to PropTypes in generated JS files.

Use cases

  • Supporting external JS clients or React components that are not written in TypeScript
  • Turn type files generated by graphql schemas into Proptypes for React components

Install

npm install interfaces-to-proptypes --save-dev

Usage

import generate from 'interfaces-to-proptypes';

generate({
  tsConfig: './tsconfig.json',
  prettierConfig: '.prettierrc',
  inputPattern: 'path/to/your/files/*.ts'
});
OptionDescriptionRequired
tsConfigRelative tsConfig file path for processing TS filestrue
prettierConfigRelative prettierConfig file path for formatting the generated JS filesfalse
inputPatternPattern or array of patterns of files to parse for interfaces and convert to proptypestrue
outputDirOutput directory to put generated JS files in, defaults to adjacent to JS filefalse

Example

input TS file:

// ./interface.ts
export interface TestInterface {
  numericField: number;
  booleanField: boolean;
  objectField: {
    numericField: number;
    booleanField: boolean;
  };
}
import generate from 'interfaces-to-proptypes';

generate({
  tsConfig: './tsconfig.json',
  prettierConfig: '.prettierrc',
  inputPattern: './interface.ts'
});

output JS file:

// ./interface.js
export const TestInterface = {
  booleanField: PropTypes.bool.isRequired,
  numericField: PropTypes.number.isRequired,
  objectField: PropTypes.shape({
    booleanField: PropTypes.bool.isRequired,
    numericField: PropTypes.number.isRequired,
  }).isRequired,
};

What about typescript-to-proptypes?

This library uses a modified version of the typescript-to-proptypes API for converting TypeScript definitions to PropTypes. The purpose of that library was to expose an API that clients could use to create their own proptype generation scripts. It did not include a script for generating those interfaces itself.

Clients using the library like Material UI have created scripts for generating prop types for certain scenarios. In that case it is used for taking JS files in a folder structure of:

ReactComponentName
  ReactComponentName.js
  ReactComponentName.d.ts

and mutating the JS file to include auto generated prop types from the declaration file.

The use case for this project is to:

  1. Bundle in a script to do the generation
  2. Not have any coupling to folder structures, declaration files or React components
  3. Not mutate input files

Thank yous

License

This project is licensed under the terms of the MIT license.