1.2.0 • Published 3 years ago

@cd2/typespec v1.2.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

Typespec

Runtime checking of javascript with strict typescript types applied

Installation

yarn add @cd2/typespec

Usage

First declare a specification which defines the expected type:

import t from "@cd2/typespec"

t.string
t.number
t.boolean
t.null
t.undefined
t.any // matches anything
t.unknown // matches anything but sets the typescript type to unknown

// a spec for an object with three properties
t.spec({
  x: t.number,
  y: t.string,
  z: t.boolean
})

t.array(t.string) // string[]
t.array({ x: t.string }) // { x: string }[]

t.partial({
  x: t.number,
  y: t.number,
  z: t.number
}) // { x?: number, y?: number. z?: number }

t.spec([t.number, t.string]) // number | string

// { x: number | undefined, y: { y1: string }, z: { a: number, b: number }[] }
t.spec({
  x: [t.number, t.undefined],
  y: { y1: t.string },
  z: t.array(t.partial({ a: t.number, b: t.number }))
})

Using the specification:

t.is(value, specification) // returns true if the value matches the specification
t.permit(value, specification) // strips away values which are not in the spec
t.invariant(value, specification) // throws an error if the type does not match

Examples

import { t } from "@cd2/typespec"

const value: unknown = { x: 1, y: 2 }

const spec = t.spec({ x: t.number, y: number })

if (t.is(value, spec)) {
  // value is { x: number, y: number }
} else {
  // value is unknown
}
import { t } from "@cd2/typespec"

const value: unknown = { name: "a name", email: "some@email.com", isAdmin: true }

const spec = t.spec({ name: t.string, email: t.string })

const sanitized = t.permit(value, spec)
// sanitized is { name: 'a name', email: 'some@email.com' }
1.2.0

3 years ago

2.0.0

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.13

5 years ago

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago