Giter VIP home page Giter VIP logo

ts-to-io's Introduction

ts-to-io

Converts TypeScript type and interface definitions into io-ts type validators.

Usage

As a script

$ npm install -g ts-to-io
$ ts-to-io file.ts

or

$ npx ts-to-io file.ts

From code

NOTE: The validator generation is not intended to be performed at runtime. You should first generate the validators locally and then include them in the program source.

import { getValidatorsFromString } from "ts-to-io"

const sourceString = `
  type Person = { name: string; age: number | null }
`

const validators = getValidatorsFromString(sourceString)

Configuration

ts-to-io supports the following config options

Key CLI opt Default Description
followImports --follow-imports false output codecs for types declared in imported files
includeHeader --no-include-header true omit io-ts import from the output

Supported types

Type Supported TypeScript codec
string string t.string
number number t.number
boolean boolean t.boolean
null null t.null
undefined undefined t.undefined
void void t.void
any, unknown any, unknown t.unknown
array Array<A> t.array(A)
record Record<K, A> t.record(K, A)
object type { name: string } t.type({ name: t.string })
interface interface I { name: string } t.type({ name: t.string })
literal 'ABC' t.literal('ABC')
partial Partial<{ name: string }> t.partial({ name: t.string })
readonly Readonly<A> -
readonly array ReadonlyArray<A> -
tuple [ A, B ] t.tuple([ A, B ])
tuple with rest [ A, B, ...C ] -
union A | B t.union([ A, B ])
intersection A & B t.intersection([ A, B ])
keyof keyof M -
recursive type type Node = { children: Node[] } -
function type fn = () => string t.Function

ts-to-io's People

Contributors

dependabot[bot] avatar juusaw avatar tkurki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ts-to-io's Issues

TypeError: Cannot read property 'escapedName' of undefined

Getting following error:
Error: Failed to generate a codec for:

Getting this is stack trace:

TypeError: Cannot read property 'escapedName' of undefined
    at Object.isArrayType (/Users/ravisharnagat/ts-2-iots/types.js:50:24)
    at /Users/ravisharnagat/ts-2-iots/index.js:90:22
    at /Users/ravisharnagat/ts-2-iots/index.js:33:48
    at Array.map (<anonymous>)
    at /Users/ravisharnagat/ts-2-iots/index.js:52:14
    at /Users/ravisharnagat/ts-2-iots/index.js:107:42
    at handleDeclaration (/Users/ravisharnagat/ts-2-iots/index.js:128:69)
    at /Users/ravisharnagat/ts-2-iots/index.js:139:21
    at visitNodes (/Users/ravisharnagat/ts-2-iots/node_modules/typescript/lib/typescript.js:18973:30)
    at Object.forEachChild (/Users/ravisharnagat/ts-2-iots/node_modules/typescript/lib/typescript.js:19206:24)

Error: Failed to generate a codec

I have no idea what might be going wrong as the actual problem is not output.

Would you be open to some refactoring with one of the following solutions:

  1. Early exit with descriptive error message
  2. Collect error messages and output them when done

For handling/collecting errors, would you prefer Either from fp-ts or go dependency free and add another argument on the visitor such as errors: Error[]?

I'm not yet sure what might be throwing errors in handleDeclaration and what kind of errors they are, but I guess those errors can be mapped to something more descriptive with file name or original declaration string etc.

I'd like to contribute to get a t-shirt from Octoberfest 😃

Union type with strings gets transformed to t.keyof

getValidatorsFromString(`type A = '1' | '2'`);

yields

import * as t from "io-ts"

const A = t.keyof({"1": null, "2": null})

instead of expected

import * as t from "io-ts"

const A = t.union([t.literal("1"), t.literal("2")])

string index signature limitation

Given some type with non-optional properties:

export interface Address {
  street_address: string;
  city: string;
  state: string;
}

we get the following io-ts codec:

const Address = t.type({street_address: t.string, city: t.string, state: t.string})

So good so far. However, if we add a string index signature:

export interface Address {
  street_address: string;
  city: string;
  state: string;
  [k: string]: any;
}

We now get the following io-ts codec:

const Address = t.record(t.string, t.unknown)

That suits the string index signature, but we've lost validation of the three required fields.

Handle interface with Date property

Hi, thanks for a potentially very useful lib!

Currently, given an interface with a date property

export interface MyInterface {
    myDate: Date;
}

the generated code does not compile

const MyInterface = t.type({myDate: t.type({toString: t.Function, toDateString: t.Function, toTimeString: t.Function, toLocaleString: t.Function, toLocaleDateString: t.Function, toLocaleTimeString: t.Function, valueOf: t.Function, getTime: t.Function, getFullYear: t.Function, getUTCFullYear: t.Function, getMonth: t.Function, getUTCMonth: t.Function, getDate: t.Function, getUTCDate: t.Function, getDay: t.Function, getUTCDay: t.Function, getHours: t.Function, getUTCHours: t.Function, getMinutes: t.Function, getUTCMinutes: t.Function, getSeconds: t.Function, getUTCSeconds: t.Function, getMilliseconds: t.Function, getUTCMilliseconds: t.Function, getTimezoneOffset: t.Function, setTime: t.Function, setMilliseconds: t.Function, setUTCMilliseconds: t.Function, setSeconds: t.Function, setUTCSeconds: t.Function, setMinutes: t.Function, setUTCMinutes: t.Function, setHours: t.Function, setUTCHours: t.Function, setDate: t.Function, setUTCDate: t.Function, setMonth: t.Function, setUTCMonth: t.Function, setFullYear: t.Function, setUTCFullYear: t.Function, toUTCString: t.Function, toISOString: t.Function, toJSON: t.Function, getVarDate: t.Function, __@toPrimitive: t.Function})})

Do you have any plans to support Dates?

Support skipImports

My types are spread into multiple files, say I have A.ts and B.ts.
A.ts imports B.ts

So if I run ts-to-io A.ts > ACodecs.ts my file has all the definitions found in B.ts.

Even if B.ts is needed and some of its code needs to be duplicated into the ACodecs.ts file, I would like to avoid the unneeded definitions (i.e. interfaces found in B.ts).

For example, if I have A.ts as:

import { DataB } from './B';

export interface DataA {
  abc: DataB;
}

and B.ts as:

export interface DataB {
  def: string;
}

I would like yarn ts-to-io A.ts --skipImports to spit out:

import * as t from "io-ts"

const DataA = t.type({abc: t.type({def: t.string})})

instead of

import * as t from "io-ts"

const DataB = t.type({def: t.string})

const DataA = t.type({abc: t.type({def: t.string})})

Nested types inlined instead of referencing

When some type refers to other type like

interface MySecondInterface {
	field: MyFirstInterface;
}

ts-to-io inlines all the fields of MyFirstInterface just like

const MySecondInterface = t.type({
	field: t.type({
		property: t.number
	});
})

Instead, I'd like to see

const MySecondInterface = t.type({
	field: MyFirstInterface // generated io-ts type name
})

Is it a goal for this project?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.