Skip to content

parse ​

Validates data and returns it if valid, or throws ValidationError. Handy on the server, where an invalid request should stop processing right away.

Signature ​

ts
function parse<S extends Schema>(schema: S, value: unknown, options?: Options): Infer<S>

Parameters ​

ParameterTypeDescription
schemaSchemaThe schema to validate against
valueunknownAny data
optionsOptions{ all?: boolean } — as in validate

Returns ​

Cleaned, typed data — the same as result.data of validate.

Throws ​

Examples ​

Express ​

ts
import { parse, ValidationError } from 'tinyval';

app.post('/users', (req, res) => {
  try {
    const user = parse(CreateUser, req.body);
    // user is validated and typed
  } catch (e) {
    if (e instanceof ValidationError) return res.status(422).json({ errors: e.errors });
    throw e;
  }
});

Environment variables ​

ts
const env = parse(
  object({
    PORT: optional(coerce.number(), 3000),
    DATABASE_URL: string(),
    DEBUG: optional(coerce.boolean(), false),
  }),
  process.env,
);
// without DATABASE_URL the app fails on startup with a clear error

See also ​