Tutorial
The language
Types
A strict, structural type checker that changes no output and names every mistake where you wrote it.
This chapter covers WebFluent's types and the checker that holds a program to them. The checker runs in wf build, wf check and the editor, before any output is written. It is strict: every value has a type the program can name. Most are worked out for you — a literal, a record, a store member, a method's result — and what cannot be worked out (an empty list's items, an action's parameters, JSON whose shape is open) is written, or the checker says where (T25, T32, T23). It is also structural: a value fits a type when it has the right fields, whatever it was declared as. The checker changes nothing in the output; it only reports.
In this chapter
- The type language, and the types that come with the language
- Records (
type), enums and the shapes of map literals - Where the checker gets a type from, and how it infers one
- Narrowing a value that may be
null - Typing data from the network
- The checks, and what the checker does not check
A first type error
This page declares an Invoice record and builds one with the wrong kind of value for total:
type Invoice { id: String, total: Number, paid: Bool = false }
page Invoices(path: "/", title: "Invoices", description: "What is owed.") {
state invoice: Invoice = Invoice(id: "INV-001", total: "120")
Heading("Invoice {invoice.id}").h1
Text("Owed: {invoice.total}")
}
The build stops, pointing at the field:
error[T01]: `total` of `Invoice` is `Number`, but `"120"` is `String`
--> src/App.wf:4:53
Writing total: 120 fixes it. Had the invoice been an untyped map, { id: "INV-001", total: "120" }, the page would build, and invoice.total would be a string at run time.
The type language
| Type | Written | Values |
|---|---|---|
| String |
|
|
| Number |
|
|
| Bool |
|
|
| List |
|
|
| Optional |
|
a value or |
| Record |
the |
|
| Enum |
the |
|
| Dictionary |
|
|
| Function |
|
|
| Result |
|
|
| JSON |
|
JSON as it arrives, whose shape is open: matched, or decoded into a type |
There is no Any and no Map (T23, T24): a value whose shape you know is a record or a dictionary, and one whose shape is open is Json.
You write a type after a colon on a state, a prop, an action parameter, a type field, a route parameter, a let or a resource. This page uses several:
page Typed(path: "/", title: "Typed", description: "State with declared types.") {
state name: String = ""
state count: Number = 0
state tags: [String] = []
state picked: String? = null
state profile: [String: String] = {}
action greet(who: String, times: Number) { log("hi {who} × {times}") }
derived pick = picked ?? "none"
Heading("Typed").h1
Text("{name} {count} {tags.length} {pick}")
Button("Go") { on click { greet(name, count) } }
}
The types the language brings with it
Eleven more types come with the language. Each is a plain JSON value at run time, with no wrapper object, so it crosses a fetch, a persist, the static paint (the HTML the build pre-renders for a page) and the template engine unchanged. .native() hands a real platform object to a library that wants one.
| Type | Carried by | Written as a literal |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
ISO 8601 |
|
|
|
milliseconds |
|
|
|
|
|
|
|
a string |
|
|
|
a string |
|
|
|
a string |
|
|
|
a string |
|
|
|
the browser's |
what a |
|
|
a string | — |
Money is held in minor units — cents, pence — so its arithmetic is whole-number arithmetic and nothing drifts. A duration is milliseconds, so it adds to a moment. uuid() is where a Uuid comes from: it uses the platform's own generator where there is one, and otherwise builds a version-4 UUID from the best randomness available.
This page books a stay with dates, money and a refined number:
type Booking {
id: Uuid
guest: Email
from: Date
nights: Number(1..=30)
total: Money
}
page Stay(path: "/", title: "Stay", description: "One booking.") {
state from: Date = @2026-03-14
state nights: Number = 5
state total: Money = €249.00
derived checkout = from.plus(days: nights)
derived late = now.date().isAfter(checkout)
Heading("Your stay").h1
Text("Out on {checkout:.date(long)}")
Text("Due {format(total)}")
if late { Alert("Checkout has passed").warning }
}
Everything the language computes is a call; everything the carrier already has is a field. So total.amount and total.currency are fields, and from.plus(days: nights) and now.date() are calls.
| Type | Methods |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Adding a month lands on a day that exists: @2026-01-31.plus(months: 1) is the 28th of February, not the 3rd of March. All of these methods also run at build time, so the static paint shows the answer instead of a blank that fills in when the page hydrates.
A literal is held to its type
A string written where one of these types is wanted is read as that type, and checked where you wrote it. The second state on this page does not build:
page Links(path: "/", title: "Links", description: "A URL held to its type.") {
state site: Url = "https://example.com" // fine
state bad: Url = "example" // T01: a URL has a scheme
Heading("Links").h1
Text("{site.host()} {bad}")
}
now
now is a DateTime that keeps itself current. It updates every minute by default, or as often as a page asks with now(every: …):
page Feed(path: "/", title: "Feed", description: "What happened lately.") {
state posted: DateTime = @2026-03-14T09:30:00Z
derived age = posted.until(now)
Heading("Feed").h1
Text("{ago(posted)} — {age.minutes()} minutes")
Text("ticking: {now(every: 1.seconds)}")
}
Read now where it is shown or in a derived value. A state takes its initial value once, so state clock = now(every: 1.seconds) stays at the moment the page opened (X06; see State and reactivity).
A condition on a type
Any type may say what its values must be. The compiler holds every value it can read to that condition, as it does to the three states on this page:
page Stay(path: "/", title: "Stay", description: "Values held to a condition.") {
state nights: Number(1..=30) = 12
state pass: String(minLength: 8) = "correcthorse"
state start: Date(after: @2026-01-01) = @2026-03-14
Heading("Stay").h1
Text("{nights} nights from {start}, {pass.length} characters")
}
The conditions are min, max, minLength, maxLength, pattern, after and before, and a range for the two ends at once: 1..=30 includes the end, 0..10 excludes it. A value that arrives at run time — typed into a field, say — is refused by validation, from the same condition, so a refined type needs no validate rule for it (see Forms).
Secret is not a string
A Secret is a string the compiler will not let escape. This page lets one escape four ways, and each is a T12:
page Login(path: "/", title: "Login", description: "Four ways a secret escapes.") {
state token: Secret = ""
persist saved: Secret = "" // kept in the browser
Heading("Signed in").h1
Text(token) // shown
Text("Bearer {token}") // in text, which is how it ends up in a URL
Button("Debug") { on click { log(token) } } // in the console, and often in a log service
}
Joining it with + or handing it to a browser global such as console, a storage or a fetch address is a T12 too, and a secret has no string members to read. Hold it in state, which ends with the visit; what must outlive the visit belongs on the server.
Your own name wins
A type the program declares takes the name back from the language. A project with its own type Color { name: String } means that record everywhere it writes Color.
Records: type
A record is a value with named, typed fields, declared with type:
enum Tone { neutral, info, danger }
type Todo {
id: String
title: String
done: Bool = false
tone: Tone = .neutral
note: String?
}
type Admin = Todo { owner: String }
page Records(path: "/", title: "Records", description: "A list of records.") {
state todos: [Todo] = [
Todo(id: "1", title: "Write the docs"),
Todo(id: "2", title: "Ship", done: true, tone: .info, note: "Friday"),
]
state special: Admin = Admin(id: "3", title: "Review", owner: "sam")
Heading("Records").h1
for todo in todos by todo.id {
Row(gap: .sm) {
Text(todo.title)
if let n = todo.note { Badge(n).info }
}
}
Text("{special.owner} owns {special.title}")
}
- You may separate fields with newlines or commas.
- You build a record by naming its fields:
Todo(id: "1", title: "x"). A field with a default may be left out, and aT?field defaults tonull. Leaving out a field with no default isC01. - A record whose fields can all be left out is built with none given,
Offers(), wherever a value goes: a prop's default (component Card(offers: Offers = Offers())), a field's default, aconst, astate, an argument. type Admin = Todo { owner: String }extends a record: anAdminhas every field ofTodo, then its own.- Records are structural:
{ id: "a", title: "b" }given where aTodois wanted is aTodo, and its fields are checked against the record's. - An answer from the network is held to the type you name for it, field by field, as it arrives —
.decode(at, message)names the field that does not fit.
Enums
An enum is a type with a fixed set of cases. A case may carry a payload — values that travel with it:
enum Size { sm, md, lg }
enum Status { idle, running(job: String), failed(reason: String), done(count: Number) }
page Enums(path: "/", title: "Enums", description: "Enums with and without payloads.") {
state size: Size = .md
state s: Status = .idle
Heading("Enums").h1
Button("Bigger") { on click { size = .lg } }
Button("Start") { on click { s = .running("build-42") } }
Text(match size { .sm { "small" } .md { "medium" } else { "large" } })
match s {
.running(job) { Text("Running {job}") }
.failed(reason) { Alert(reason).danger }
.done(n) { Text("{n} done") }
else { Text("Idle") }
}
}
- You write a case as
.name. On its own it is a case of an enum not yet known; where aSizeis wanted it becomes aSize, and.hugethere isT02. - A case with a payload,
.failed("x"), is checked like a call. Amatcharm binds the payload:.failed(r)givesrthe typeString. - At run time a bare case is its name and a case with a payload is a list,
["failed", "timed out"], sosize == .lgstill compares cases. - A
matchwith noelsemust give every case an arm (T15). - An enum prop is written to a component's root element as
data-<prop>(see Enum props).
Note
Coming from TypeScript in React or Vue? A union of strings such as "idle" | "running" | "failed" becomes an enum, and a field that only some states have becomes that case's payload: .failed(reason: String). A match then has to give every case an arm. See Coming from React.
Shapes of map literals
A map literal has the fields it was written with. { name: "", age: 0 } has the shape { name: String, age: Number }, and reading form.nam is T05, with the fields it does have. A shape fits a record with the same fields, and any shape it agrees with. An empty {} and a literal with a spread say nothing about their keys: where one is held, say what it holds — state seen: [String: Bool] = {} — or the checker asks (T25).
page Shapes(path: "/", title: "Shapes", description: "A map literal with a shape.") {
state form = { name: "", age: 0, tags: ["new"] }
Heading("Shapes").h1
Input(bind: form.name, label: "Name")
Text("{form.name} is {form.age} with {form.tags.length} tags")
}
What agrees with what
A value fits where a type is wanted when it is that type, with nothing converted on the way:
- A map literal is a record's only when its fields are the record's: a field the record lacks is
T05, a required one left outC01, one of the wrong typeT01— where it is written, and when a map kept in a state is given as the record later.{ ...todo, done: true }is aTodoagain. - One value, one type. The branches of an
ifor amatch, a list's items and the two sides of??make one value:if ok { 1 } else { "none" }isT27.nullon one side makes itT?. - A condition is a
Bool.if countisT29; write what it asks,count != 0,name != "",user != null. ABool?is a condition, itsnullfalse. A fallback for null is??, not||. - No conversions.
+adds two numbers, joins two strings or adds two durations; text and a number meet in a splice,"Total: {n}"(T18). ADateis shown through a splice that says how,"{due:.date(long)}", and aDurationsays its unit,500.ms(T34). AUrl, anEmail, aColorand aUuidare strings wherever text is wanted. Jsonis matched or decoded, never read as a record, a list or a number (T28):User.decode(raw).
type Todo { id: String, title: String, done: Bool = false }
page Agree(path: "/", title: "Agree", description: "Values that are what they say.") {
state todo = Todo(id: "1", title: "Milk")
state left = 3
state due: Date = @2026-03-14
state nickname: String? = null
Heading("Agree").h1
Button("Done") { on click { todo = { ...todo, done: true } } }
if left != 0 { Text("{left} left") }
Text("Due {due:.date(long)}")
Text(nickname ?? "friend")
}
Dictionaries, functions and aliases
A dictionary holds values of one type under keys of another: [String: Number] is a score per name, [Region: Money] a price per region of an enum. It is written as a map literal where one is wanted, every value checked against its type and, for an enum's keys, every key against its cases. A key may be missing, so reading one — scores["ada"] or scores.ada — gives a Number?. Its methods are keys(), values(), entries() (each { key, value }), has(k), and with(k, v) and without(k), which make a copy with one key more or one fewer.
A function type is written with its parameters in parentheses and its result after ->: (Todo) -> Bool. () is nothing: () -> () takes and returns nothing. A prop that takes a lambda declares one, and what the caller passes is held to it, parameters and result.
type Name = T gives a type a second name, read as the type it names:
type Scores = [String: Number]
enum Region { north, south }
component Label(_ region: Region, describe: (Region) -> String) {
Text(describe(region))
}
page Dictionaries(path: "/", title: "Dictionaries", description: "Values by key, and a function as a prop.") {
state scores: Scores = { ada: 3, bo: 5 }
state prices: [Region: Number] = { north: 10, south: 20 }
Heading("Dictionaries").h1
Text("{scores.values().sum()} points; Ada has {scores.ada ?? 0}")
Text("North costs {prices.north ?? 0}")
Button("Add Cy") { on click { scores = scores.with("cy", 7) } }
Label(.south, describe: r => "Region {r}")
}
An action that returns a value says what with -> T, and every return in it is held to that; its callers see the type it declares. A lambda's parameter may say its type too, where nothing it is handed to does:
type Todo { id: String, title: String, done: Bool = false }
store Todos {
state items: [Todo] = []
action open() -> Number {
return items.filter(todo => !todo.done).length
}
}
page Typed(path: "/", title: "Typed", description: "An action's result and a typed lambda.") {
use Todos
derived byTitle = (a: Todo, b: Todo) => a.title.localeCompare(b.title)
Heading("Typed").h1
Text("{Todos.open()} open")
for todo in Todos.items.slice().sort(byTitle) by todo.id { Text(todo.title) }
}
JSON, decoding and results
Json is JSON as it arrives — an object, a list, a string, a number, a flag or null — with nothing yet known about it. It is the language's own enum, and a value of it is written by its case, Json.null, Json.string("x"). Any plain value — a string, a number, a list, a record — fits where Json is wanted; a Json value is read by matching it:
page Kinds(path: "/", title: "Kinds", description: "A JSON value read by what it is.") {
state raw: Json = Json.array([Json.number(1), Json.number(2)])
Heading("Kinds").h1
match raw {
.object(fields) { Text("An object of {fields.keys().length} fields") }
.array(items) { Text("A list of {items.length}") }
.string(s) { Text("The text {s}") }
.number(n) { Text("The number {n}") }
.bool(b) { Text("The flag {b}") }
.null { Text("Nothing") }
}
}
More often it is decoded: every record, enum and alias a program declares has decode, which checks a value against the type, field by field, as the page runs. Settings.decode(raw) is a result, Settings ! DecodeError: .ok(settings) when it fits, or .err(e) with e.at saying where it went wrong ($.tags[0]) and e.message what is wrong there (is 1, not a String):
type Settings { theme: String, columns: Number }
page Restore(path: "/", title: "Restore", description: "Settings decoded from text.") {
state text = "{\"theme\": \"dark\", \"columns\": 3}"
Heading("Restore").h1
Textarea(bind: text, label: "Settings", rows: 3)
match Settings.decode(JSON.parse(text)) {
.ok(s) { Text("{s.theme}, {s.columns} columns") }
.err(e) { Alert("{e.at} {e.message}").danger }
}
}
A result is written T ! E — a T, or an error of E — and T! for one whose error is a request's failure. An action declares one with -> T ! E, and -> ! E (or -> !) when it returns nothing but may fail. A match on a result gives both .ok and .err an arm, or an else.
Where types come from
The checker reads a type from five places.
What another declaration, another file or a caller sees is declared; what only the body sees is inferred. So the checker never has to work one declaration out to check another, and the order declarations are written in never changes a type.
Declared: annotations, a type's fields, an enum's cases, a page's route parameters, a component's props, an action's, an event's and a slot's parameters (T32 without one), and an action's result (-> T).
Inferred: a literal; a list of literals ([1, 2] is [Number]); a record construction; a derived value from its expression; a state from its first value, when that value says everything; a for binding from the list's item type; a match arm's binding; an if let binding; a lambda's parameters from what the method expects (items.filter(item => …) gives item the item type).
A first value says everything when it is a number, a string, a case, a record or a list or map with items. An empty list, an empty map, null or open JSON says nothing of what will be kept, so the state declares it:
type Todo { id: String, title: String }
type User { name: String }
page Board(path: "/board", title: "Board", description: "Todos.") {
state draft = ""
state items: [Todo] = []
state picked: User? = null
Heading("Board").h1
Input(bind: draft, label: "New todo")
Button("Add") { on click { items = items.concat([Todo(id: uuid(), title: draft)]) draft = "" } }
for todo in items by todo.id { Text(todo.title) }
if let user = picked { Text("Picked by {user.name}") }
}
Written state items = [], it is T25, and the fix writes the type the body assigns it. A lambda written where nothing says its parameters' types — derived byName = (a: User, b: User) => … — says them (T32).
A derived value is worked out after what it reads, wherever that is: one below it, another store's, a store declared further down. Two that read each other with neither declared have nothing to start from (T35).
From the registry: the type of every built-in prop, and what a bind: needs — Checkbox and Switch a Bool, Slider a Number, Input a String or a Number by its input type.
From the method tables:
- On a
String:trim,toLowerCase,toUpperCase,replace,slice,padStart,repeat,capitalize,truncate(n)→String;length,indexOf→Number;includes,startsWith,endsWith→Bool;split→[String]. - On a list:
map→[U]from the lambda;filter,slice,concat,sort,sortBy,unique,take,flatMap→[T];find,first,last→T?;some,every,includes→Bool;length,sum,indexOf,findIndex→Number;join→String;groupBy→[K: [T]];reduce→ the initial value's type. - On a
Number:toFixed,toString→String.
A method the type does not have is T16, with the nearest one it does. The full lists are in Built-ins.
From stores: Todos.items has the type of the store's state, and Todos.add the signature of its action.
From the browser table: window, document, JSON, Math, Date, the timers, an event a handler is given and an element a ref: names (see Built-ins).
From a script's JSDoc: what a project script's function takes and returns, a @typedef's record, a class's methods — and what it returns is checked as the page runs (Call your own script).
A name keeps the type it was declared or inferred with: state x = 1 stays a Number, and assigning a string to it later is T01.
Bidirectional inference
The checker works in both directions. When the context wants a type, it checks the expression against that type; otherwise it reads the type off the expression. The comments show what each derived value is inferred to be:
type Row { id: Number, label: String, score: Number? }
page Infer(path: "/", title: "Infer", description: "Types the checker works out.") {
state rows: [Row] = [Row(id: 1, label: "a"), Row(id: 2, label: "b", score: 9)]
derived labels = rows.map(r => r.label) // [String]
derived best = rows.find(r => r.score != null) // Row?
derived total = rows.reduce((n, r) => n + (r.score ?? 0), 0) // Number
derived kind = if total > 5 { "high" } else { "low" } // String
derived firstScore = best?.score ?? 0 // Number
derived joined = labels.join(", ") // String
Heading("Infer").h1
Text("{joined} {kind} {firstScore}")
}
The rules for operators and forms:
a ?? bisawithout itsnull, joined withb.a?.bisb's type made optional, and the rest of the chain with it.ifandmatchused as values have the type both arms fit: the same type,T?when one arm isnull; arms with no type in common areT27.-,*,/and%give aNumber;+gives aStringwhen either side is one; comparisons and&&,||,!give aBool.await http.get(…)is what you annotate it as:let r: [Row] = try await http.get(…).- A browser global is what the browser's table says:
JSON.parse(text)isJson,localStorage.getItem(k)isString?; a handler's event is the browser's (on keydown(e)is aKeyboardEvent), aref:anElement, andcatch eanError. let { a, b } = mandlet [x, y] = lbind the fields and the items.
Narrowing optionals
A value of type T? may be null, so you must narrow it — prove it is not null — before you read a field or method off it. Reading one without narrowing is T04. Each of these forms narrows a name within its branch:
type Todo { id: String, title: String, note: String? }
page Narrow(path: "/", title: "Narrow", description: "Values that may be null, narrowed.") {
state sel: Todo? = null
state todo: Todo = Todo(id: "1", title: "x")
Heading("Narrow").h1
if let n = todo.note { Text("{n.length} chars") }
if sel != null { Text(sel.title) }
derived label = if sel != null { sel.title } else { "none" }
Text(todo.note ?? "no note")
Text(sel?.title ?? "nothing selected")
Button("Pick") { on click { sel = todo } }
}
Narrowing follows the flow of a block: it holds in the branch the condition guards, not after it. A check for null also narrows the else branch, and the code after if x == null { return }. An item at a fixed index, such as todos[0], may be missing, so it counts as T? unless a condition like todos.length > 0 encloses it.
A list narrows too: xs.filter(x => x != null) is a list of the items that are there, so a [Todo?] filtered that way is a [Todo] whose items need no ?..
Note
Coming from React? {user && <Profile user={user} />} becomes if let u = user { Profile(u) }, and inside the branch u is a User, not a User?. undefined is not a separate value to check for: a value that may be missing is T?, and missing is null. See Coming from React.
Warning
Splicing a value that may be null into text shows the word null on the page. The checker warns (T19); say what to show instead with ??, as in Text(todo.note ?? "no note").
Typing data from the network
The checker cannot see what a URL will return, so an http.get says it: annotate the resource or the local variable with the type it holds (N11 without one). The answer is held to that type as it arrives, in every build:
type Deploy { id: String, status: String, startedAt: String }
page Deploys(path: "/", title: "Deploys", description: "A typed resource.") {
resource deploys: [Deploy] = http.get("/api/deploys")
Heading("Deploys").h1
match deploys {
.loading { Spinner }
.failed(e) { Alert("Failed: {e.message}").danger }
.loaded(rows) {
for d in rows by d.id { Text("{d.id} {d.status} {ago(d.startedAt)}") }
}
}
}
In every build — under wf serve and deployed alike — each response is held to its declared type as it arrives, and one that does not fit fails as .decode(at, message), naming the place, such as $[1].status is missing.
When the server publishes an OpenAPI specification, let it write the contract instead: wf api add openapi.json --name Backend writes every endpoint, parameter, response and error as files, and turns each named schema into a type, or an enum for a string with cases (see Data and APIs). An api you write by hand types its calls the same way: get users() at "users" -> [User].
The checks
The type checker reports these codes. All are errors except T19, which is a warning.
| Code | When |
|---|---|
|
|
A value of the wrong type given to a prop, a state, a field, a parameter, an assignment, an argument, or a |
|
|
A case the enum does not have |
|
|
A field or method read off a value that may be |
|
|
A field or method a record or shape does not have |
|
|
A member or action a store does not have, or an endpoint a service does not have |
|
|
A list, a record or an action used as a condition, which is always true |
|
|
A |
|
|
An |
|
|
A call with the wrong arguments: too many or too few, a name the callee does not take, or one of the wrong kind |
|
|
A |
|
|
A |
|
|
A name, or a function called, that nothing declares — which the browser would throw on |
|
|
A comparison that is always the same: |
|
|
A |
|
|
A method a number, a string or a list does not have, with the nearest one it does |
|
|
An async action's result used before it is awaited, or |
|
|
Arithmetic on something that is not a number, or |
|
|
A value that may be |
|
|
A list or a record shown as text |
|
|
A read's |
|
|
A handler that names more values than its event sends |
|
|
Two values with no type in common made into one: an |
|
|
A |
|
|
A condition — |
|
|
Data from outside the program — a |
|
|
A |
Most findings come with a hint: a conversion (Number(value), "{value}"), the cases an enum takes, the fields a record has, or one of the narrowing forms above. wf explain T05 prints a code's full entry, and Diagnostics has every code with an example.
What the checker does not check
- It does not check a lambda's body against a return type unless the lambda is handed to a function type, which says one.
- It does not know what a server will send until it sends it: an
httpcall names its type, or the service is described with anapi, and what arrives is held to it at run time.
In the editor
Hover shows a name's inferred type: state draft: String, derived remaining: Number, Todos.add: (String) -> (). Completion after . offers a record's fields, an enum's cases where one is wanted, and the methods of a String, a Number or a list. A type error appears as a diagnostic on the argument it belongs to. To set up the editor, see Editors.
Quick reference
| Syntax | Meaning |
|---|---|
|
|
Annotate a state; props, parameters, fields and |
|
|
A list, a value that may be |
|
|
A dictionary, a function, nothing |
|
|
Another name for a type |
|
|
What an action returns; a lambda's parameter type |
|
|
JSON as it arrives, and its cases |
|
|
Read a type out of JSON; a result, and its cases |
|
|
Declare a record |
|
|
Extend a record |
|
|
Build a record |
|
|
Declare an enum, with an optional payload per case |
|
|
Write a case |
|
|
A type with a condition |
|
|
Narrow or read through |
|
|
Type data from the network |
Common mistakes
A field read off a value that may be null. email is a String?, so .length would throw when it is missing:
type User { name: String, email: String? }
page P(path: "/", title: "T", description: "D") {
state user: User = User(name: "Ada", email: null)
Heading(user.name).h1
Text("{user.email.length} characters")
}
Narrow it first, if let mail = user.email { Text("{mail.length} characters") }, or read through it with a fallback, user.email?.length ?? 0. See T04.
A misspelled field on a map literal. A map literal has the fields it was written with, so a typo is caught where it is read:
page P(path: "/", title: "T", description: "D") {
state form = { name: "", age: 0 }
Heading("Profile").h1
Input(bind: form.name, label: "Name")
Text("Hello, {form.nmae}")
}
Use one of the fields the hint lists, form.name. See T05.
A value that may be null spliced into text. The page would show the word null when there is no note:
type Todo { id: String, title: String, note: String? }
page P(path: "/", title: "T", description: "D") {
state todo: Todo = Todo(id: "1", title: "Ship")
Heading(todo.title).h1
Text("Note: {todo.note}")
}
Say what to show instead, Text("Note: {todo.note ?? "none"}"), or draw the line only when there is a note with if let. See T19.
Going further: Expressions lists every operator and helper a typed value can be used with.
What you learned
-
Annotate state, props and parameters, and declare records with
type -
Use the built-in types:
Date,Money,Duration,Url,Secretand the rest -
Declare an
enumwhose cases carry payloads -
Narrow a value that may be
nullwithif let,?.and?? -
Type data from the network with an annotated
resource