Runtype converts Typescript type aliases, interfaces, and enums to Javascript that can be used during runtime
npm install @dollarshaveclub/runtype
*
Features
Installing
Usage
Support
License
*
> Runtype converts Typescript type aliases, interfaces, and enums to Javascript that can be used during runtime
bash
npm i -g @dollarshaveclub/runtype # Install globally or --save-dev
`Usage
First things first, you need to have some typescript that you'd like to transpile to javascript.
$3
`bash
Input: STDIN, Output: STDOUT
$ echo 'type ID = string | number' | runtype >> ./output.jsInput: Disk, Output: STDOUT
$ runtype -f './files/*/.ts' >> ./output.jsInput: Disk, Output: Disk
$ runtype -f './files/*/.ts' -o ./output.jsDebug
echo 'type ID = string | number' | runtype -d
`$3
`javascript
import { parse, render } from '@dollarshaveclub/runtype'
import fs from 'fs'const data = parse(['./files/my-types.ts'])
console.log(data.aliases.ID)
fs.writeFileSync(render(data), './output.js')
`$3
Once you've transpiled your typescript, import it in your project to be compiled into your apps build.The transpiled API allows you to validate your data with the types and interfaces defined in your typescript files. They are functions that will throw errors if the
data provided is invalid.
`javascript
import {
aliases: { ID },
interfaces: { Product },
} from './output.js'ID(123)
ID('123')
ID(true) // Throws an error
Product({ sku: 'M-EXEC-1', price: 5.00 }) // etc
`Additional APIs are available to work with.
`javascript
import {
runtypes, // All of your types/interfaces organized neatly
validate, // A function that validates data, returns true or error messages
resolveType, // A function that converts a value into a type
aliases, // An object containing all of your type aliases
interfaces, // An object containing all of your interfaces
enums, // An object containing all of your enums
} from './output.js'console.log(runtypes) // neat
validate('ID', 5) // true
validate('ID', ['test']) // ['ID value is invalid']
resolveType(5) // "number"
resolveType([]) // "array", etc
aliases.ID(true) // throws an error
interfaces.Product({ / etc / }})
interfaces.CartAddEvent({
cart: enums.Carts.Gift, // Specify the gift cart as an enum
})
`*
Support
The following features are supported by Runtype. Contributions are always welcome!
$3
`typescript
type ID = number
`$3
`typescript
type mixed = string | number | boolean | object | symbol | null | undefined
`$3
`typescript
interface Product {
id: string | number, // Union Types
sku: string,
price: number,
type: 'product', // Literal Values
description?: string, // Optional Properties
parent: Product, // Reference Types
childProducts: Product[], // Reference Array Types
benefits: string[] // Primitive Array Types
}
`$3
`typescript
enum PaymentMethods {
Credits = 'credits',
Card = 'card',
PayPal = 'paypal',
}
``