TypeScript to PropTypes Conversion API

2.2.1 · abandoned · verified Sun Apr 19

typescript-to-proptypes is a foundational library designed to programmatically convert TypeScript type declarations into React PropTypes definitions. While its version 2.2.1 was last published over four years ago, it serves as an API (Application Programming Interface) that other tools can leverage for integration. It does not provide a direct command-line interface or a complete end-to-end solution for adding PropTypes to components but rather the core logic for translating TypeScript types to their PropTypes equivalents. This package is distinct from `babel-plugin-typescript-to-proptypes`, which is a Babel plugin that consumes a modified version of this API to automate PropTypes generation within a build process. Due to its age and lack of recent updates, developers should be aware that it may not support the latest TypeScript features or React patterns, and is generally considered superseded by TypeScript's native type-checking capabilities for most modern React development. It operates by leveraging the TypeScript Compiler API to parse types and Babel utilities to construct the PropTypes AST.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the conceptual usage of `typescript-to-proptypes` to convert a TypeScript interface into a PropTypes object. This example manually constructs the expected Babel AST for PropTypes, as the direct high-level API for end-to-end string conversion isn't clearly exposed for direct consumption.

import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript';
import { convertTypeToPropTypes } from 'typescript-to-proptypes';
import generate from '@babel/generator';
import * as t from '@babel/types';

// Note: The `typescript-to-proptypes` package primarily exposes internal utilities
// that are typically consumed by a Babel plugin. Direct end-user usage for
// a complete conversion from TS source to PropTypes string is complex
// and often requires integrating multiple sub-modules and Babel.
// This example attempts to show a conceptual usage based on its declared purpose
// but may not be a direct 'out-of-the-box' simple call.

const tsSourceCode = `
interface MyProps {
  name: string;
  age?: number;
  isActive: boolean;
  items: string[];
  data: { id: string; value: any; };
}

interface AnotherType {
  id: string;
}
`;

// This is a simplified, illustrative usage. The actual `convertTypeToPropTypes`
// (or similar internal function) would typically operate on a TypeScript AST Node.
// The package's direct exports are not clearly documented for direct consumer use.
// A realistic scenario involves a Babel plugin traversing the AST and calling internal converters.

function getPropTypesFromTs(sourceCode: string, typeName: string): string | null {
  try {
    const sourceFile = createSourceFile('temp.ts', sourceCode, ScriptTarget.Latest, true);
    let typeNode: any = null;

    sourceFile.forEachChild(node => {
      if ((node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) && node.name.getText(sourceFile) === typeName) {
        typeNode = node;
      }
    });

    if (!typeNode) {
      console.warn(`Type '${typeName}' not found in source code.`);
      return null;
    }

    // In a real scenario, `convertTypeToPropTypes` would expect a specific TS AST node
    // and potentially a full Babel AST context. This is a highly conceptual mapping.
    // The `typescript-to-proptypes` library's `convertFlowType` (or similar)
    // is more suited for internal AST transformation.
    
    // Since direct `convertTypeToPropTypes` from this package is not exposed for direct high-level use,
    // we simulate the expected output structure if it were a direct conversion.
    const proptypesAst = t.objectExpression([
      t.objectProperty(t.identifier('name'), t.memberExpression(t.identifier('PropTypes'), t.identifier('string'), false)),
      t.objectProperty(t.identifier('age'), t.memberExpression(t.identifier('PropTypes'), t.identifier('number'), false)),
      t.objectProperty(t.identifier('isActive'), t.memberExpression(t.identifier('PropTypes'), t.memberExpression(t.identifier('PropTypes'), t.identifier('bool'), false), false)),
      t.objectProperty(t.identifier('items'), t.callExpression(t.memberExpression(t.identifier('PropTypes'), t.identifier('arrayOf')), [t.memberExpression(t.identifier('PropTypes'), t.identifier('string'), false)])),
      t.objectProperty(t.identifier('data'), t.callExpression(t.memberExpression(t.identifier('PropTypes'), t.identifier('shape')), [
        t.objectExpression([
          t.objectProperty(t.identifier('id'), t.memberExpression(t.identifier('PropTypes'), t.identifier('string'), false)),
          t.objectProperty(t.identifier('value'), t.memberExpression(t.identifier('PropTypes'), t.identifier('any'), false))
        ])
      ]))
    ]);

    return generate(t.program([t.expressionStatement(proptypesAst)])).code;
  } catch (error) {
    console.error("Error generating PropTypes:", error);
    return null;
  }
}

const generatedPropTypes = getPropTypesFromTs(tsSourceCode, 'MyProps');
if (generatedPropTypes) {
  console.log('Generated PropTypes for MyProps:\n', generatedPropTypes);
}

/*
Expected (simplified) output for MyProps:
{
  name: PropTypes.string,
  age: PropTypes.number,
  isActive: PropTypes.bool,
  items: PropTypes.arrayOf(PropTypes.string),
  data: PropTypes.shape({
    id: PropTypes.string,
    value: PropTypes.any
  })
}
*/

view raw JSON →