Quicktype TypeScript Input

23.2.6 · active · verified Sun Apr 19

The `quicktype-typescript-input` package serves as an input module for the `quicktype` code generation tool, specifically enabling the use of TypeScript source code as a schema definition. `quicktype` itself is a robust utility that generates strongly-typed models and serializers from various inputs like JSON, JSON Schema, TypeScript, and GraphQL queries. This package allows developers to define their data structures using TypeScript interfaces or types, and then generate client libraries or data models in numerous target programming languages, including C#, Go, Rust, Java, Swift, Python, and even TypeScript itself with runtime validation. Currently, the package is at version `23.2.6`, aligning with the main `quicktype` project's stable releases. Its primary differentiator is simplifying the process of creating type-safe data access layers by automating boilerplate code, allowing developers to focus on application logic rather than manual data model definition and deserialization.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically use `quicktype-typescript-input` to take a TypeScript source string defining interfaces and enums, and then generate corresponding type definitions in different target languages like TypeScript or C# using the `quicktype-core` library.

import { quicktype, InputData } from 'quicktype-core';
import { TypeScriptInput } from 'quicktype-typescript-input';

async function generateTypesFromTypeScript(typescriptSource: string, targetLanguage: string, typeName: string): Promise<string> {
  const tsInput = new TypeScriptInput();
  await tsInput.addSource({
    name: typeName,
    samples: new Set([typescriptSource])
  });

  const inputData = new InputData();
  inputData.addInput(tsInput);

  const { lines } = await quicktype({
    inputData,
    lang: targetLanguage,
    typeName,
    rendererOptions: {
      'just-types': 'true' // Common option to only generate types, no serialization code
    }
  });

  return lines.join('\n');
}

const myTypeScriptSource = `
interface User {
  id: string;
  name: string;
  email: string;
  isActive: boolean;
  createdAt: Date;
}

enum UserRole {
  Admin = 'admin',
  Editor = 'editor',
  Viewer = 'viewer',
}
`;

// Example 1: Generate TypeScript interfaces from TypeScript source
generateTypesFromTypeScript(myTypeScriptSource, 'typescript', 'UserAndRole')
  .then(output => {
    console.log('Generated TypeScript:\n', output);
  })
  .catch(error => console.error('Error generating TypeScript:', error));

// Example 2: Generate C# classes from TypeScript source
generateTypesFromTypeScript(myTypeScriptSource, 'csharp', 'UserAndRole')
  .then(output => {
    console.log('\nGenerated C#:\n', output);
  })
  .catch(error => console.error('Error generating C#:', error));

view raw JSON →