@cd2/typespec
v1.2.0
Published
Runtime checking of javascript with strict typescript types applied
Downloads
70
Readme
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: "[email protected]", isAdmin: true }
const spec = t.spec({ name: t.string, email: t.string })
const sanitized = t.permit(value, spec)
// sanitized is { name: 'a name', email: '[email protected]' }