A TypeScript/JavaScript library to help with runtime validation of structured data.
Consumers define Shapes that represent the structure of their data. Consumers call validateDataShape
to validate some data matches their Shape.
npm install shape-tape
import { s, validateObjectShape } from "shape-tape"
// Define a shape.
const resourceShape = s.object({
id: s.string({regex: /^[a-zA-Z0-9\-_]{10}$/}),
state: s.union([s.literal("pending"), s.literal("active"), s.literal("removed")]),
createdAt: s.integer()
})
// Validate that some object matches your shape.
const goodData = JSON.parse("{\"id\":\"ui_1zoEJ18\",\"state\":\"active\",\"createdAt\":1700354795466}")
const resource = validateDataShape({ data: goodData, shape: resourceShape })
// Safely access the validated and typed data.
if (resource.state === "active") ...
...
// Data that doesn't match your shape causes a ShapeValidationError.
const badData = JSON.parse("{\"id\":\"\",\"state\":\"active\",\"createdAt\":1700354795466}")
const resource = validateDataShape({ data: badData, shape: resourceShape })
// ^ throws ShapeValidationError "Parameter \"id\" is invalid."
If you're using TypeScript you can use the shape's TypeScript type.
import { ShapeToType } from "shape-tape"
type Resource = ShapeToType<typeof resourceShape>
...
const resource: Resource = ...
Please see the unit test demonstrating this example.
Please see the low level documentation for more details.