pipetype
v0.1.1
Published
> **Runtime schemas with TypeScript‑style unions via real `|`.** > PipeType models types as **bigint flags**. You compose **unions** with bitwise **OR** and use those flags inside **object schemas** that validate at construction time and on every assign
Readme
PipeType
Runtime schemas with TypeScript‑style unions via real
|.
PipeType models types as bigint flags. You compose unions with bitwise OR and use those flags inside object schemas that validate at construction time and on every assignment.
⚠️ Experimental Library: PipeType is an experimental project exploring bitwise operations for runtime validation. It is not intended as a replacement for mature libraries like Zod or Valibot. For production applications, we recommend using established validation libraries. This project serves as a proof-of-concept for alternative approaches to runtime type validation.
Quick look
import { Type, string, number, boolean, array, literal, validate } from "pipetype"
// 1) Natural unions with real "|"
const StringOrNumber = string | number
const isStringOrNumber = validate(StringOrNumber)
isStringOrNumber("ok") // true
isStringOrNumber(42) // true
isStringOrNumber(true) // false
// 2) Schemas: validated on create and on each assignment
Type.User = {
id: string | number, // union works inside schemas
name: string,
email: string,
isActive: boolean,
}
const user = Type.User({
id: "u_1",
name: "Jane",
email: "[email protected]",
isActive: true,
})
user.id = 123 // ✓ ok
user.id = false // ✗ throws ValidationError
// 3) Arrays (element validation) and literals (ad‑hoc enums)
Type.TodoList = {
title: string,
items: array(string),
}
Type.Status = {
value: literal("active") | literal("inactive") | literal("pending"),
updatedAt: string,
}Install
npm i pipetype
# or
pnpm add pipetype
# or
yarn add pipetypeWhy this exists
Most validators treat unions as a DSL call (z.union([...]), S.union(...)). PipeType treats types as bit masks so A | B is a real union. That keeps declarations short and lets the same primitives power schemas that enforce types both at construction and during writes.
Core API (stable surface)
Primitive type flags
string, number, boolean, bigint, symbol, nil, undef, nullish, any, unknown, never, date
Each is a bigint mask. You can use them directly in unions or inside schemas.
import { string, number, validate } from "pipetype"
const mask = string | number // 1n | 2n -> 3n
const ok = validate(mask) // (v: unknown) => boolean
ok("x") // true
ok(1) // true
ok(true) // falsevalidate(maskOrValidator)
Curried helper that returns a predicate for a mask (or a named validator). Handy for guards and tests.
const isString = validate(string)
if (!isString(maybe)) throw new Error("need a string")Type — schemas and named validators
Schemas: assign a plain object of field → type to
Type.YourName, then call it as a factory:Type.Person = { name: string, age: number, address: { street: string, city: string, zipCode: string | number, }, } const p = Type.Person({ name: "Bob", age: 30, address: { street: "123 Main", city: "NYC", zipCode: 10001 }, }) p.address.zipCode = "10002" // ✓ p.address.zipCode = null // ✗ throwsNamed validators: you can attach your own predicate functions on
Typeand use them in schemas:Type.email = (v: unknown) => typeof v === "string" && v.includes("@") Type.Account = { id: string, email: Type.email, // field must satisfy your predicate }
Note: Custom validators are function predicates. They can be used as field types; unions of primitive masks are the primary composition mechanism.
array(elementType)
Define homogeneous arrays and validate each element on write:
Type.Tags = { tags: array(string) }
const t = Type.Tags({ tags: ["a", "b"] })
t.tags = ["ok", 1] // ✗ throws (non‑string element)literal(value)
Create a literal type and combine with | for enum‑like fields:
const Active = literal("active")
const Inactive = literal("inactive")
const Pending = literal("pending")
Type.Job = { status: Active | Inactive | Pending }Error handling
- Invalid construction or assignment throws a
ValidationErrorwith a useful path message. - Prefer
validate(...)when you want a non‑throwing boolean guard.
try {
user.id = false
} catch (e) {
console.error(String(e)) // e.g., "ValidationError: $.id expected (string|number) got boolean"
}Real‑world patterns
Discriminated unions (string literal tags)
const KindA = literal("a")
const KindB = literal("b")
Type.Node = {
kind: KindA | KindB,
value: string | number,
}
const n = Type.Node({ kind: "a", value: "x" })
n.kind = "b" // ✓
n.kind = "oops" // ✗Config with flexible IDs
Type.Service = {
id: string | number,
name: string,
enabled: boolean,
}Nested arrays of objects
Type.List = {
title: string,
items: array(Type.Service),
}Limitations & roadmap
- Intersections (
A & B) — not implemented. Intersections require all checks to pass; the bit‑mask model handles unions (ANY) cleanly, but intersections (ALL) need sequential predicate logic. Future work may add function‑based intersections. - Coercion / parsing — PipeType validates values you give it; it doesn’t coerce. Add your own parsing before construction if needed.
- Schema inference — This is a runtime lib. You still get good DX in TS, but static type inference is intentionally minimal compared to parser‑based libs.
Appendix A — How the bitwise model works
- Bit allocation — each primitive validator is assigned a unique bit in a
bigint(e.g.,1n,2n,4n, …). - Union via
|— composing unions is OR’ing those flags (1n | 2n = 3n). - Membership via
&— to validate, PipeType maps a runtime value to its primitive flag and checks(flag & mask) !== 0n. - Schemas — objects returned by
Type.Name(initial)are Proxies;settraps validate new values against each field’s mask (recurse for nested schemas / arrays). - Why no intersections — a mask can’t require multiple independent predicates at once; intersections need function composition that runs all checks.
Appendix B — Complete, runnable examples
B1. User + Status
import { Type, string, number, boolean, array, literal, validate } from "pipetype"
Type.Status = {
value: literal("active") | literal("inactive") | literal("pending"),
updatedAt: string,
}
Type.User = {
id: string | number,
name: string,
email: string,
isActive: boolean,
tags: array(string),
status: Type.Status,
}
const u = Type.User({
id: "u1",
name: "Ada",
email: "[email protected]",
isActive: true,
tags: ["founder"],
status: { value: "active", updatedAt: new Date().toISOString() },
})
u.tags.push("admin") // ✓
u.status.value = "bad" // ✗ throwsB2. Guards with validate()
import { string, number, validate } from "pipetype"
const isStringOrNumber = validate(string | number)
function takesStringOrNumber(x: unknown) {
if (!isStringOrNumber(x)) throw new Error("bad input")
}License
MIT
