gen-ts-type

Generate Typescript type from sample data


Keywords
typescript, reflection, types, code generation, cli
License
BSD-2-Clause
Install
npm install gen-ts-type@1.8.0

Documentation

gen-ts-type

Generate Typescript type from sample data

npm Package Version

Installation

npm i -g gen-ts-type

Usage

From cli

echo 'export type Package = ' | tee package.d.ts
format=1 allowEmptyArray=1 allowMultiTypedArray=1 gen-ts-type package.json | tee -a package.d.ts

From typescript

import { genTsType } from 'gen-ts-type';
import * as fs from 'fs';

const UserType = genTsType(
    { user: 'Alice', friends: [{ user: 'Bob', since: new Date() }] },
    { format: true },
  );
const code = `export type User = ${UserType};`
fs.writeFileSync('types.ts', code);

Above example generate into:

export type User = {
  user: string;
  friends: Array<{
    user: string;
    since: Date;
  }>;
}

Features

Supported features

  • primitive types
    • string
    • number
    • boolean
    • bigint
    • Date
    • symbol (not specific)
  • Array (single-type / union-type)
  • Object (strict-type / optional-type)
  • named custom type

Todo features

  • Tuple (specific-type array) (e.g. [number, string, string])
  • specific symbol / string / number
  • Enum