ChoiceSchema.get()method
Get an unknown value as one of the allowed choices, or undefined if it isn't one.
get(unsafeValue: unknown = this.value): O | undefined
new ChoiceSchema<O, I>({ one = "choice", title = "Choice", placeholder = `No ${one}`, options, value, input, ...rest }: ChoiceSchemaOptions<O, I>)| Param | Type | |
|---|---|---|
rest | ChoiceSchemaOptions<O, I> | Options for ChoiceSchema. required |
.options | PossibleChoiceOptions<O> | Specify correct options using a dictionary of entries. required readonly |
.value | OI | Default option for the value. readonly |
.input | ChoiceInputType | Input control hint for downstream UIs. Defaults to "radio" for 8 or fewer options, otherwise "select" readonly |
| Return | |
|---|---|
ChoiceSchema<O, I> | Schema that validates a value against a fixed set of allowed string choices. |
| Property | Type | |
|---|---|---|
.options | ChoiceOptions<O> | Dictionary of allowed options for a ChoiceSchema in { key: title } format. required readonly |
.input | ChoiceInputType | Input control hint for a ChoiceSchema: "radio" for radio inputs, or "select" for a <select>. required readonly |
Schema that validates a value against a fixed set of allowed string choices.
options, otherwise it is rejected.format().Validates that a value is one of a known set of options — designed to power a <select> field in HTML. The validated type is the union of the option keys.
CHOICE is the sugar factory that builds a ChoiceSchema from either an array of strings (keys and labels are the same) or an object (keys are the validated values, object values are display labels).
import { CHOICE } from "shelving/schema";
// Array form — keys and labels are the same.
const STATUS = CHOICE(["draft", "published", "archived"] as const);
STATUS.validate("published"); // "published"
STATUS.validate("deleted"); // throws "Unknown value"
// Object form — keys are validated values, object values are display labels.
const Priority = CHOICE({ low: "Low priority", high: "High priority" });ChoiceSchema is iterable and exposes .keys() and .entries() for building select menus. It does not implicitly default to the first option; pass value if you want a preselected choice.
input tells a form UI which control to show. It defaults from the number of options: "radio" for 8 or fewer, "select" for more. Set it to always use one control:
import { ChoiceSchema } from "shelving/schema";
const UNIT = new ChoiceSchema({ options: ["kg", "g", "lb"], input: "select" }); // Always a <select>.
const SIZE = new ChoiceSchema({ options: ["s", "m", "l", "xl"], input: "radio" }); // Always radios.Get an unknown value as one of the allowed choices, or undefined if it isn't one.
get(unsafeValue: unknown = this.value): O | undefined
Validate an unknown value as one of the allowed choices.
validate(unsafeValue: unknown = this.value): O