Type Safe Object Notation & Validation
- 🧱 Fonctional
- 🔷 Immutable
- ✅ Well tested
pnpm add tosi
yarn
and npm
also work
import { t } from 'tosi'
const { t } = require('tosi')
import { t } from 'tosi'
const name = t.string()
name.parse('nyan') // return "nyan"
name.parse(42) // throw TypeCheckError
import { t } from 'tosi'
const user = t.object({
name: t.string(),
age: t.number(),
admin: t.boolean(),
})
user.parse({ name: 'nyan', age: 42, admin: true })
type User = t.infer<typeof user>
// { name: string, age: number, admin: boolean }
It is strongly recommended to activate the strict mode of TypeScript which will activate all checking behaviours that results in stronger guarantees of the program's correctness.
By default tosi
parse objects in STRICT
mode, this means that all undefined values in a scheme will be considered as an error. You can change this behaviour globally or locally, the procedure is documented here.
- tosi
- Install
- Examples
- Strict mode
- Table of contents
- API
- First level types
- literal(value)
- array(type)
- tuple(...type)
- tuple(type[])
- tuple(type[] as const)
- object(schema)
- object(schema, mode)
- object helpers
- union(...type)
- union(type[])
- union(type[] as const)
- optional(type)
- enum(...string)
- enum(string[])
- enum(string[] as const)
- enum(object)
- enum(object as const)
- enum(enum)
- nativeEnum(enum)
- instanceof(type)
- date()
- record(type)
- set(type)
- set(...type)
- set([type, ...type])
- map(keyType, valueType)
- map(schema)
- promise(type)
- function()
- function(args)
- function(args, returns)
- function(args, returns, implement)
- preprocess(filter, type)
- postprocess(filter, type)
- postprocess(filter, inputType, outputType)
- Type helpers
- Contributing 💜
t.string()
t.number()
t.bigint()
t.boolean()
t.symbol()
t.date()
t.nan()
t.finite()
t.infinity()
t.integer() // Alias: int()
t.unsignedNumber() // Alias: unumber()
t.unsignedInteger() // Alias: uinteger(), uint()
t.undefined()
t.null()
t.void()
t.any()
t.unknown()
t.never()
const life = t.literal(42)
const love = t.literal(true)
const name = t.literal('nyan')
life.value // type => 42
const arr1 = t.array(t.string()) // string[]
const arr2 = t.array(t.boolean()) // boolean[]
const tpl = t.tuple(t.string(), t.number(), t.string()) // [string, number, string]
const tpl = t.tuple([t.string(), t.number(), t.string()]) // [string, number, string]
💔 The following code does not work, TypeScript can not infer array values properly. Use the as const
workaround to do this.
const types = [t.string(), t.number(), t.string()]
const tpl = t.tuple(types) // [string, number, string]
const types = [t.string(), t.number(), t.string()] as const
const tpl = t.tuple(types) // [string, number, string]
const user = t.object({
name: t.string(),
age: t.number(),
admin: t.boolean(),
})
type User = t.infer<typeof user>
// { name: string, age: number, admin: boolean }
By default tosi
parse objects in STRICT
mode, but you can change the mode globally or locally.
There are three modes:
STRICT
: Will raise an error if a key is not defined in the schema.STRIP
: Strips undefined keys from the result and does not raise an error.PASSTHROUGH
: Keeps undefined keys and does not raise an error.
Change the default mode globally.
t.defaultSettings.objectTypeMode = t.ObjectTypeMode.STRIP
Change the mode locally.
const schema = { a: t.string(), b: t.string() }
const input = { a: 'a', b: 'b', c: 'c' }
const user = t.object(schema, t.ObjectTypeMode.STRICT)
user.parse(input) // throws an TypeParseError
const user = t.object(schema, t.ObjectTypeMode.STRIP)
user.parse(input) // { a: string, b: string }
const user = t.object(schema, t.ObjectTypeMode.PASSTHROUGH)
user.parse(input) // { a: string, b: string, c: string }
t.object(schema).strict()
// same as
t.object(schema, t.ObjectTypeMode.STRICT)
t.object(schema).strip()
// same as
t.object(schema, t.ObjectTypeMode.STRIP)
t.object(schema).passthrough()
// same as
t.object(schema, t.ObjectTypeMode.PASSTHROUGH)
const uni = t.union(t.string(), t.number()) // string | number
const tpl = t.union([t.string(), t.number(), t.string()]) // string | number
💔 The following code does not work, TypeScript can not infer array values properly. Use the as const
workaround to do this.
const types = [t.string(), t.number(), t.string()]
const tpl = t.union(types) // string | number
const types = [t.string(), t.number(), t.string()] as const
const tpl = t.union(types) // string | number
const user = t.object({
name: t.string(),
age: t.optional(t.number()),
})
// { name: string, age?: number }
const myEnum = t.enum('UP', 'DOWN', 'LEFT', 'RIGHT')
// === "UP"
myEnum.enum.UP
// error: PLOP does not exists
myEnum.enum.PLOP
// error: it is read-only
myEnum.enum.DOWN = "prout"
(property) enum: {
readonly UP: "UP"
readonly DOWN: "DOWN"
readonly LEFT: "LEFT"
readonly RIGHT: "RIGHT"
}
myEnum.options[1] // === "DOWN"
(property) options: ["UP", "DOWN", "LEFT", "RIGHT"]
myEnum.parse(myEnum.enum.LEFT) // => "LEFT"
myEnum.parse('LEFT') // => "LEFT"
myEnum.parse('2') // => "LEFT"
myEnum.parse(2) // => "LEFT"
myEnum.parse('PLOP') // error: expected '0|1|2|3|UP|DOWN|LEFT|RIGHT' got 'string'
type MyEnum = t.infer<typeof myEnum> // => "UP" | "DOWN" | "LEFT" | "RIGHT"
function move(direction: MyEnum) {
// direction === "DOWN"
}
move(myEnum.enum.DOWN)
const myEnum = t.enum(['UP', 'DOWN', 'LEFT', 'RIGHT'])
💔 The following code does not work, TypeScript can not infer array values properly. Use the as const
workaround to do this.
const values = ['UP', 'DOWN', 'LEFT', 'RIGHT']
const myEnum = t.enum(values)
const myEnum = t.enum(['UP', 'DOWN', 'LEFT', 'RIGHT'] as const)
const values = ['UP', 'DOWN', 'LEFT', 'RIGHT'] as const
const myEnum = t.enum(values)
const myEnum = t.enum({ UP: 'UP', DOWN: 'DOWN', LEFT: 42, RIGHT: 43 })
💔 The following code does not work, TypeScript can not infer object properties properly. Use the as const
workaround to do this.
const values = { UP: 'UP', DOWN: 'DOWN', LEFT: 42, RIGHT: 43 }
const myEnum = t.enum(values)
const values = { UP: 'UP', DOWN: 'DOWN', LEFT: 42, RIGHT: 43 } as const
const myEnum = t.enum(values)
enum MyEnum {
UP = 'UP',
DOWN = 'DOWN',
LEFT = 42,
RIGHT,
}
const myEnum = t.enum(MyEnum)
Alias: enum(enum)
enum MyEnum {
UP = 'UP',
DOWN = 'DOWN',
LEFT = 42,
RIGHT,
}
const myEnum = t.nativeEnum(MyEnum)
class MyClass {}
const instance = new MyClass()
t.instanceof(MyClass).parse(instance) // passes
t.instanceof(MyClass).parse('nyan') // fail
t.date().parse(new Date()) // passes
t.date().parse('2022-01-12T00:00:00.000Z') // passes
t.date().parse('not a string date') // fail
t.record(t.string()) // { [x: string]: string }
t.record(t.number()) // { [x: string]: number }
t.record(t.date()) // { [x: string]: Date }
Testing a single type on the entire set
t.set(t.string()) // Set<string>
Testing a union of types on the entire set
t.set(t.union(t.string(), t.boolean(), t.string())) // Set<string|boolean>
Same as tuple(...type) but test if the input is an instance of Set.
Testing a tuple of types on the Set
t.set(t.string(), t.boolean(), t.string()) // Set<[string, boolean, string]>
t.set([t.string(), t.boolean(), t.string()]) // Set<[string, boolean, string]>
t.map(t.string(), t.number()) // Map<string, number>
t.map(t.date(), t.string()) // Map<Date, string>
Same as object(schema) but test if the input is an instance of Map.
const map = new Map()
t.map({ name: t.string(), size: t.string() }).parse(map)
const promise = t.promise(t.number())
await promise.parse(Promise.resolve(42)) // resolve: 42
await promise.parse(Promise.resolve('42')) // reject: expected 'number' got 'string'
await promise.parse(42) // reject: expected 'Promise' got 'number'
const func = t.function()
type Func = t.infer<typeof func> // () => void
const func = t.function([t.string(), t.number()])
type Func = t.infer<typeof func> // (arg_0: string, arg_1: number) => void
const func = t.function([t.string()], t.boolean())
type Func = t.infer<typeof func> // (arg_0: string) => boolean
const args = [t.string(), t.boolean()] as const
const returns = t.union(t.string(), t.number())
const func = t.function(args, returns, (input, toInt) => {
// input type is string and toInt type is boolean
return toInt ? Number.parseInt(input) : input.toUpperCase()
})
type Func = t.infer<typeof func> // (arg_0: string, arg_1: boolean) => string | number
If you want to modify the input before it is parsed you can use the preprocess
type as follows.
const toString = t.preprocess(input => String(input), t.string())
toString.parse('42') // => "42"
toString.parse(42) // => "42"
If you want to modify the output after it is parsed you can use the postprocess
type as follows.
const postprocess = t.postprocess(input => input + 2, t.number())
postprocess.parse(40) // => 42
postprocess.parse('42') // throws: "expected 'number' got 'string'"
If you want to modify the output after it is parsed you can use the postprocess
type as follows.
const postprocess = t.postprocess(
input => String(input),
t.number(),
t.string(),
)
postprocess.parse(40) // => "42"
postprocess.parse('42') // => throws: "expected 'number' got 'string'"
If you want to avoid the parse method throws an error you can use the .safeParse()
method instead.
t.bigint().safeParse(42n)
// => { success: true, data: 42n }
t.bigint().safeParse(42)
// => {
// "error": [TypeParseError: expected 'bigint|undefined' got 'number'],
// "success": false,
// }
t.bigint().optional() // => bigint | undefined
// same as
t.optional(t.bigint())
t.string().preprocess(input => String(input))
// same as
t.preprocess(input => String(input), t.string())
Alias: .transform()
t.number().postprocess(input => input + 2)
// same as
t.postprocess(input => input + 2, t.number())