Skip to content
Playground(another site)

Refined-type API

A refined type is a base type plus one or more predicates:

type Age = Int where InRange(0, 150)
type Username = String where MinLength(3) && MaxLength(20)

Predicates are combined with &&. A refined type emits a branded type plus a constructor object with .of — its only runtime constructor (ADR 0182). A value enters the type through .of (checked) or compile-time literal admission; there is no .unsafe escape hatch (that is opaque-only).

PredicateHolds when
NonNegativevalue ≥ 0
Positivevalue > 0
InRange(lo, hi)lo ≤ value ≤ hi (inclusive)

These apply to Int, Float and Decimal. The InRange bounds are literals of the base’s own type: 0, 0.0 or 0.00d.

PredicateHolds when
NonEmptylength ≥ 1
MinLength(n)length ≥ n, counted in code points
MaxLength(n)length ≤ n, counted in code points
Length(n)length = n, counted in code points
Matches(regex)the whole string matches regex (anchored)
IsoDatea calendar date, exactly YYYY-MM-DD (years 0000-9999), and a date that exists
Crona valid Cloudflare cron schedule: five fields separated by exactly one space (cron)

A String’s predicate length is in code points, so an emoji counts once; it agrees with chars() and with the maxLength of the published OpenAPI. s.length() is different: it counts UTF-16 code units, so "🙂".length() is 2.

IsoDate is the date half of RFC 3339 and the date rule Instant.fromIso applies: months and days must exist (2028-02-29 and 2000-02-29 do, 2026-02-29, 1900-02-29, 2026-02-30 and 2026-13-01 do not), and nothing but zero-padded YYYY-MM-DD is accepted. A string literal is checked at compile time; .of, Json.decode and the HTTP boundary (a 400 RefinementViolation) apply the same rule. A Day stays a String everywhere else. For the day’s first instant, Instant.fromIso("\(day)T00:00:00Z") is always Some.

Cron admits exactly the schedules Cloudflare’s cron triggers accept, which a Matches regex cannot express (a range must run low to high, a step must be at least one, L, W and # appear only in certain fields). A literal is checked at compile time, and .of, Json.decode and the HTTP boundary apply the same rule. The prelude type CronSchedule = String where Cron names it. OpenAPI exports Cron as type: string with x-bynk-format: cron.

A predicate must apply to the base type (bynk.types.predicate_base_mismatch). An InRange with lo > hi is rejected (bynk.types.inverted_range), as is a set of predicates that admit no value (bynk.types.empty_refinement) or a negative length (bynk.types.negative_length). An invalid regex is bynk.types.invalid_regex. A Matches, IsoDate or Cron refinement may be followed by @example("…"), a test witness for Val that the compiler checks against the refinement (@example). The emitted boundary check runs a Matches regex under the platform’s backtracking RegExp, on untrusted input, so the compiler rejects a regex that can match the same text along many paths (a denial-of-service risk):

  • bynk.types.catastrophic_regex: exponential ambiguity, such as nested repetition ((a+)+), overlapping alternatives ((a|a)+, (\d|\d\d)+) or a bounded repeat inside a loop or of an ambiguous body ((a{2,3})+, (?:a|a){0,24}). It also covers a regex the compiler cannot analyse, such as a backreference inside an unbounded repeat. Nesting alone is not the test: a repeated group that must open with a character the preceding repetition cannot match is unambiguous and accepted, as in the slug [a-z]+(-[a-z]+)*, [a-z0-9]+(\.[a-z0-9]+)* and \d+(,\d{3})*. An optional separator ([a-z]+(-?[a-z]+)*) is ambiguous and refused.
  • bynk.types.polynomial_regex: two repetitions that can split the same text (\d*\d*). With a MaxLength, Length or IsoDate (ten characters) predicate in the same refinement small enough for the pattern’s degree (at most 3,162 characters for two overlapping repetitions, 215 for three) it is only a warning, bynk.types.polynomial_regex_capped, because length predicates are always checked before Matches.

(foo|foobar)+ is accepted: its alternatives overlap, but each text splits into them only one way.

Age.of(value) // Result[Age, ValidationError]

.of returns a Result whenever the type has predicates. A named type with no predicate (type Id = Int) has nothing to check, so Id.of(n) returns Id directly; add a where clause later and every call site that can now fail becomes a type error until it handles the failure. Use .of for values not known at compile time (input, variables). See Define a refined type and validate untrusted input.

Tip. In VS Code, hover a refined type and follow Try values… to see example values and check your own against the predicate, with the failing clause named. See editor support.

A literal written where a refined type is expected is checked at compile time and admitted directly (lowering to an inline brand cast), with no Result. Admission applies in these positions:

  • return position (block tail);
  • a let with a type annotation;
  • an Ok/Some/Err payload;
  • a refined-typed call argument.

A literal that violates the predicate is a compile error (bynk.refine.literal_violates). Opaque types are excluded from admission. Admitted literals are compile-time literals only — integers, strings, booleans, and () — not arithmetic expressions or identifiers.

See The refined-literal admission model for the rationale.

A value crossing a context boundary (a consumes call argument, or a service’s return value) is compared structurally, and a refinement on the sending side is admitted where the receiving side expects a weaker one: String where MaxLength(4) is accepted where MaxLength(8) is expected, Positive where NonNegative is, and an InRange(1, 5) where InRange(0, 10) is. The reverse is bynk.boundary.structural_mismatch. Order and spelling do not matter (NonEmpty is MinLength(1)), and the numeric and length predicates are decided by interval containment; Decimal bounds compare by value. Matches is only equal to an identical pattern.

This is a boundary rule. Inside a context, type Short = String where MaxLength(4) is still not assignable to type Long = String where MaxLength(8): named types stay distinct.

A runtime value can be narrowed to a refined type with is. value is Refined runs the type’s predicates at runtime and yields a Bool; where that truth gates the branch (an if body, the right of &&), the value is narrowed to the refined type — so it can be passed where the refined type is expected, without going through .of:

commons demo
type Quantity = Int where InRange(1, 100)
fn double(q: Quantity) -> Int {
2
}
fn classify(n: Int) -> Int {
if n is Quantity {
double(n) // n : Quantity here
} else {
0
}
}
  • The value must be an identifier to be narrowed (a let binding or a parameter); f(x) is Quantity is a valid check but narrows nothing.
  • The refined type’s base must match the value’s (bynk.types.is_base_mismatch).
  • This is the flow-sensitive counterpart to .of: .of(v) returns a Result for the untrusted case; is narrows in a guard. Refinements are not preserved through arithmetic (a + b of two refined Ints is a plain Int) or through an inherited base method (see below): a read that leaves the refined type yields the base type.

See Narrow and bind with is.

A refined type inherits its base type’s read-only kernel methods. Calling one on a refined value type-checks exactly as it does on the base, and the result is the base type — never the refined type:

commons demo
type Name = String where NonEmpty
fn shout(n: Name) -> String {
n.toUpper()
} // n.toUpper() : String
fn size(n: Name) -> Int {
n.length()
} // n.length() : Int
fn tag(n: Name) -> String {
"user:".concat(n)
} // a refined arg widens too

This is the same rule refinement already follows for arithmetic, comparison, and ordering keys: a refined value widens to its base wherever it is read, so no new mental model is needed. The inherited set is each base’s entire kernel — the String, numeric (Int, Float, Decimal), Duration, Instant, and Bytes kernels defined in the static semantics. Bool has no kernel, so a Bool-based refinement inherits nothing.

Two boundaries:

  • Declared methods win. If the refined type declares an instance method, it takes precedence; the inherited kernel is consulted only when the type declares no method of that name.
  • Opaque types do not inherit. An opaque type deliberately does not widen to its base, so a kernel call on it stays bynk.types.method_not_found. Reach its base through the type’s own methods (or .raw, inside the defining commons).