Browse guides

Validate values and access nested data

Normalize profile input before rendering allowed and nested values.

The example selects the accepted fields, writes and reads the profile name, validates the role and renders `Arya: editor`.

Table of contents

Main APIs

ensureIn
Checks whether a value belongs to an allowed collection.
get
Reads a nested value by path and returns the provided fallback when needed.
pick
Creates an object with the selected keys from a source value.
set
Updates a nested object path.
ts
import { mount } from "valyrian.js";
import { ensureIn, get, isFiniteNumber, pick, set } from "valyrian.js/utils";

type Input = {
  role: string;
  pageSize: number;
  profile: { name: string };
  ignored: boolean;
};

const input: Input = {
  role: "editor",
  pageSize: 20,
  profile: { name: "Arya" },
  ignored: true,
};
const safe = pick<Input, "role" | "pageSize">(input, ["role", "pageSize"]);
const role: string = safe.role;
set(input, "profile.name", "Arya");

if (!ensureIn(role, ["viewer", "editor"])) {
  throw new TypeError("Unsupported role");
}
if (!isFiniteNumber(safe.pageSize)) {
  throw new TypeError("Page size must be finite");
}

const name = get(input, "profile.name", "Anonymous");
mount("body", () => `${name}: ${role}`);

Limit

Each validator checks only the rule represented by its API.

Exact references