nenu-lang / defaults-and-fallbacks
Stable

Defaults And Fallbacks

  • A default block supplies fields for one named type or enum variant.
  • A container fallback belongs to one array or map declaration and changes missing-index results from optional to required.
  • Default blocks and collection fallbacks solve different problems and use different syntax.

Defaults For Named Types

code
1type ExpenseDraft {2  title: string3  amount: number4  note: string?5}67default ExpenseDraft {8  title: "Untitled expense"9  amount: 010}

A default target must exist, each field must exist on that target, and every default value must match its field type. Only one default block may target the same named type.

Defaults For Enum Variants

code
1enum ExpenseStatus {2  Draft,3  Open,4  Submitted,5  Approved { approved_at: time },6  Rejected { reason: string },7  Settled8}910default ExpenseStatus.Rejected {11  reason: "No reason supplied"12}

Target the structured variant with Enum.Variant. A unit variant has no fields to default.

Container Fallbacks

code
1type BalanceLabel {2  label: string3  amount: number4}56BalanceLabel { label: "Unknown", amount: 0 } [] rows = []7BalanceLabel first = rows[0]89BalanceLabel { label: "Unknown", amount: 0 } {} by_member = {}10BalanceLabel missing = by_member["missing"]

The fallback value appears before the collection marker. Missing array positions and map keys return that value, so the result is not optional.

Fallback Ownership Rules

  • The fallback must satisfy the named element type.
  • It is evaluated once when the declaration runs.
  • It belongs only to that declaration.
  • Assigning the collection to a normal array or map does not copy fallback behavior.
  • Normal collections without a fallback keep optional index results.
  • An empty object fallback must be spaced: BalanceLabel {} []. Compact BalanceLabel{}[] means an array of maps.

Choose The Right Mechanism

NeedUse
Fill omitted fields on a named valuedefault Type { ... }
Fill fields on a structured enum variantdefault Enum.Variant { ... }
Replace one absent scalar expressionoptional ?? fallback
Handle present or absent brancheswith or without
Replace a missing array index or map keyA declaration-level container fallback.
Represent no elementsAn empty array or map.

Common Mistakes

MistakeCorrection
Use a default when absence is meaningfulKeep the value optional.
Assume a fallback persists dataUse an entity default and explicit save when persistence is intended.
Use container fallbacks in Page ScriptInitialize browser state explicitly.
Define two defaults for the same targetKeep one unambiguous default block.

Continue Learning