Skip to content
Logo

T.optional

An absence primitive: a field that might be left out, present as undefined, or present with a value. It only makes sense inside T.object(...).

T.optional(inner); // ~33% omitted, ~33% undefined, ~33% value
T.optional(inner).weighted({ omitted: 1, undefined: 1, value: 2 });

By default, each outcome has a 1/3 chance. You can change the odds of any outcome, and weights are relative. A weight of 0 turns that outcome off, so { omitted: 0 } is always present, either as undefined or with a value. It throws if every weight is 0. Negative weights, NaN, and Infinity are invalid.

A weight of 0 changes the odds, not the type. T.optional(x).weighted({ omitted: 0 }) still types the key as optional. To change the type, use a narrower kind, such as T.undefinable or a required field.

To force the field to be left out, pass Omitted to .override() or .fabricate(overrides):

import { Omitted } from "@ghostry/fabricator";
 
WidgetFabricator.fabricate({ nickname: Omitted });

For a field that is either left out or present with a value, never undefined, use T.omittable. For a key that is always present but whose value may be undefined, use T.undefinable.