Duolith docs

Types

How a page's types are checked, what is caught when the app is built, and what is not. The guide for writing typed pages is docs/guide/types.md.

One type system: TypeScript's

Markup has no type system of its own (decision 0095). Every page and component becomes one TypeScript file, its script view (crates/script-view): the script block as written, then the markup as ordinary TypeScript in a function that sees the script's names.

<text>{post.caption}</text>            __duolith_text(post.caption);
<input type="email" bind:value={d} />  __duolith_attribute<"text" | "email" | ...>("email");
                                       d = __duolith_bind<string>(d);
<show when={user}>…</show>             if (user) { … }
<list each={posts} as="post">          for (const post of __duolith_items(posts)) { … }
<Card title={post.caption} />          __duolith_place(Card, { title: (post.caption) });

Each copied piece maps back to where it is written, so an error shows on the page's own text; nothing is ever reported in generated text. The types an attribute and an event take come from the language definition: accepts and receives in spec/language/elements.yaml.

The editor (the language server) and duolith check check this same view, with the same declarations and options (decisions 0096, 0097); the few differences are listed under "The editor and the build" below. duolith build (for the web and with --target native) and duolith dev run duolith check's checks before they write anything; a native build reports their errors before any error of its own (E0200 and on). No flag skips them, and nothing in a project can switch them off: // @ts-nocheck, // @ts-ignore and // @ts-expect-error, in any letter case, and /// <reference> are E0357; a value typed any used anywhere, the any keyword, Function, eval, text given to setTimeout or setInterval, !, as unknown as, as never, a cast from unknown to a type parameter and let x!: T are E0358; and declare is E0359. A project's tsconfig.json cannot loosen the options either, in the editor or the build: every strict option is set by name.

These are refused twice. The analyzer (crates/analyzer/src/escape_hatches.rs) reads the text, so its errors are quick. The refusals (packages/language-server/src/refusals.ts), which the build's checker and the editor both run, refuse from what TypeScript resolved, so another spelling cannot get past: globalThis.eval, (0, eval), const run = eval and globalThis[key] or Reflect.get(globalThis, key) where the key is "eval"; Function(...) without new, and the Function that .constructor gives; CallableFunction and globalThis.Function; a ///<reference> with no space; any import that reaches outside the project; and every use of any, below. One mistake is reported once: a page the analyzer already found an error in has its checker errors held back in the build, and an error the analyzer reported is not repeated by the refusals at the same place.

  • Where a directive counts. @ts-ignore and @ts-expect-error count at the start of a comment line, and @ts-nocheck in the file's leading comments, where TypeScript honours them. A comment that only mentions one (/** We never use @ts-ignore. */) is fine.
  • **A cast from unknown is allowed on purpose.** const post = data as Post, where data is already unknown, is how data of unknown shape (parsed JSON, a message) is given a type, and it is written where that data comes in. Refusing it would leave a type guard as the only way, and a guard is trusted just the same. What is refused is as unknown as, which throws away a type the checker knew, as never, which gives a value every type at once, and a cast from unknown to a type parameter, below.
  • **typeof eval in a type is allowed.** It names a type and runs nothing. A value of that type is refused where it comes from eval itself.

Uses of any

A value typed any is never checked, so E0358 refuses every use of one in a page, a component or the project's own .ts and .d.ts files, whatever produced the any: JSON.parse, Response.json(), Reflect.get, import(path) with a path held in a variable, a type alias that resolves to any, or a package's declarations. Refusing each source of any misses the next way to spell it; refusing its uses does not. This is what typescript-eslint's no-unsafe-* rules do, built into the type check. A value typed any may not be:

  • read from (data.name, data[key]), called, constructed with new, extended by a class, used as a key, spread, destructured or iterated over;
  • assigned, passed, returned, put in an object or a list, or given a type with as or satisfies, where the type it lands in is not unknown or any: an initialiser, an argument, a return, a prop in markup and a binding. A variable with no type written takes the any, so const data = JSON.parse(text) is refused too;
  • a markup expression: shown as text, given to an attribute, listed by <list each> or tested by <show when>.

A value whose type holds an any, such as the Promise<any> of response.json() or an any[], may not land where that place is typed (Promise<Post>, Post[]). An any is reported once, where it is first used: data.a.b is one error, at data.

The way out is unknown, then narrowing: receive the value as unknown and check its shape before use.

type Saved = { name: string };

function isSaved(value: unknown): value is Saved {
  return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string";
}

const data: unknown = JSON.parse(localStorage.getItem("saved") ?? "null");
const name = isSaved(data) ? data.name : "Guest";

A type alias whose result is any can still be written, but nothing can be done with a value of it: type Ret<F> = F extends (...a: never[]) => infer R ? R : never gives any for Ret<typeof JSON.parse>, and const u: Ret<typeof JSON.parse> = 1 is allowed, but u.deep, const n: number = u and {u} in markup are each E0358.

A generic function cannot launder unknown into any type its caller picks: function lie<T>(x: unknown): T { return x as T; } is E0358 at as T, since a cast from unknown to a type parameter checks nothing. A cast to a type the function names (x as Post) is a cast from unknown, allowed as above.

What is checked, exactly:

  • Every page and component in the project, and every kit part a page uses.
  • Each of the project's own .ts and .d.ts files that a page or component imports, directly or through another file, with the same options. Its errors are reported at its own line. A .d.ts file is read as declarations, and a file the analyzer cannot parse is reported (E0007), never taken as clean. A file nothing imports is not checked.
  • No file outside the project's folder may be in the program unless it is a package under node_modules (E0356), so no file outside it is ever used unchecked. It is reported at the import that brought it in, however that is written: a relative or absolute path, backslashes, import("…") in a type, import x = require(…), or a package whose types point outside. A file reached through a link inside the project is checked where the link is.
  • Not checked: .js files (a value import from one is E0356, and a type import finds no types) and packages in the project's own node_modules folder, whose declarations are used as they are written. A folder named node_modules deeper in the project holds the project's own files, and they are checked.

Columns in an error are counted in characters, in the build and in the editor alike, so a line with "é" or an emoji before the error reads the same everywhere.

The editor and the build

In a page or component, the editor shows every type error and every refusal (E0340 to E0349, E0355 to E0359) that duolith check reports, at the same line and column: the analyzer runs in the editor's compiler service, and the refusals in the language server, over the same program as its TypeScript service (packages/language-server/src/features/refusals.ts). These differ, and only these:

  • A page with a structural error (such as an unknown element, E0101): the build holds back that page's type errors and refusals until it is fixed, so one mistake is reported once. The editor shows them at once.
  • **A project .ts or .d.ts file.** The language server shows its refusals (E0356 to E0358 from what TypeScript resolved, every use of any included) when the editor gives it the file. The VS Code extension gives the server only page files, so there a .ts file shows TypeScript's own errors and its refusals show in the build. The analyzer's text checks of a .ts file run only in the build: a file that does not parse (E0007), declare and namespace (E0359), and !, as unknown as and let x!: T (E0358). A .ts file nothing imports is checked by the editor, and by the build once a page imports it.
  • Checks of the whole project, which need every file at once: the route table (E0141 to E0146), links and images against the pages and public/ (E0353, E0354), and the checker itself failing (E0350 to E0352). These are reported by the build only.

The matrix

Every typed position, what caught a mistake in it before this work, and what catches it now. "Now" is the same in the editor and in the build. Each row has a failing project and a clean counterpart in tests/typed-markup/<fixture>, whose expected.txt lists the exact errors; a Rust test (crates/cli/src/typecheck/tests.rs) and a language server test (packages/language-server/test/typed-markup.test.ts) both assert it.

PositionExample of a mistakeEditor beforeBuild beforeNowFixture
Script blockconst label: string = count (a number)yesnoE0340script-block
Text expression{post.captoin}; {post.liked} (a boolean, shown as "false")name onlynoE0341, E0340text-expression
Attribute with an expression<image src={size}> (a number), <button disabled={busy}> (a string), rows={"3"}nonoE0340element-attribute
Attribute written as a word<input type="emial">; type={kind} and detent={detent} holding words the attribute does not knownonoE0340attribute-words
Event handlerevent.valeu in on:input; on:press={save} where save takes a numberyes (decision 0027)noE0341, E0340event-handler
Binding to an element<slider bind:value={volume}> holding a string; bind:value of string | undefinednonoE0340, both directionsbind-element
Binding to a component<Sheet bind:open={open}> holding a string; <Select bind:value={pick}> holding a numbernonoE0340, both directionsbind-component
Props given to a component<Card title={42}>, count="2"nonoE0340 at the propcomponent-props
Props of a kit part<Button variant="primry">, <TextField label={3}>no (the kit was any)noE0340kit-part-props
Slots and pieces{count.trim()} in a piece, {cuont} in the slotname onlynoE0341slots-and-pieces
Listeach={count} (not a list); key={post} (an object); {i.toUpperCase()} on the indexitem onlynoE0340, E0341list
Show and otherwise{user.name} outside <show when={user}> or in its <otherwise>; narrowed insidenonoE0343show-otherwise
Route parametersroute().slug on pages/post/[id].duo; id used as a numbernonoE0341, E0340route-params
Route queryquery.tab; const tab: string = query["tab"] (may be missing)nonoE0345, E0340route-query
Layoutroute().id in a layout, which serves many routesnonoE0345, E0340layout
Data layerfeed.data.length before it loaded; feed.data[0]; post.title on a type without itnonoE0343, E0340, E0341data-layer
Platform effectsshare({ link: … }), an option share does not take; its result used as a booleanyesnoE0341, E0340effects-import
Implicit anyfunction add(amount)yesnoE0344implicit-any
Exhaustivenessa switch over a union that misses a member, in a function returning a valuenonoE0346exhaustive-switch
Missing moduleimport { format } from "@duolith/missing"; stat from @duolith/clientyesnoE0347, E0341missing-module
Lines with CRLF, accents and emoji{café.nope} after éé 😀 on a CRLF line: the column is the same in the editor and the buildnonoE0341unicode-and-crlf

The structural checks (E0101 to E0170) and the type check run together. A file with a structural error has its type errors held back, so one mistake is never reported twice (a missing required prop is E0113, not also a type error); every other file's type errors are reported in the same run, so all of them show at once.

A project's own .ts files, the comments and any refused, and quoted values are checked by Rust tests in crates/cli/src/typecheck/tests.rs, the analyzer's own tests and the checker's (packages/checker/test/checker.test.ts). One project with refusals in a page and in a .ts file is checked by both sides: the_editor_and_the_build_report_the_same_refusals in the Rust tests and packages/language-server/test/refusals.test.ts in the editor's.

The examples/typed-errors app shows eight of these errors in one small page, and fails on purpose; CI's clean build loop leaves it out, its native build loop checks that it fails with exactly those errors, and its test asserts its exact errors.

Options

Pages are checked with strict and the stricter options listed in decision 0097: noUncheckedIndexedAccess, exactOptionalPropertyTypes, noPropertyAccessFromIndexSignature, noImplicitReturns, noFallthroughCasesInSwitch, noImplicitOverride, useUnknownInCatchVariables, and unreachable code and unused labels as errors. A project cannot loosen them.

One rule is the markup's own, and matches what the runtime does: undefined given to an attribute or to an optional prop means "left out". An attribute set to undefined is removed, and a prop set to undefined takes its default.

Compile-time safety

Each way a page could fail when it runs, and what stops it when the app is built.

What would fail at run timeCaught byCode
A misspelt element, attribute or event (<buton>, on:presss)the analyzer, from the language definitionE0101, E0102
A class or theme token that does not exist (text-inkk, bg-nope)the analyzer, from the utilities and the themeE0103
An unknown icon, role, kit part or piecethe analyzerE0123 to E0128
A component that does not exist, or a prop it does not have, or a required prop left outthe analyzerE0110 to E0113
Two pages for one route, a bad route segment, a parameter the route lacksthe route tableE0141 to E0146
A link with a refused scheme (javascript:)the analyzerE0170
A link to a page that does not exist: href="/setings" or href={"/setings"}; navigate("/setings") or `navigate(/setings), under any import name or through the namespace; a path held in a top-level const or in a property of a top-level const object written as const; a guard's redirect; signIn.required("/sing-in")`the build, against the route table (decision 0099)E0353
An image from public/ that is not there (src="/images/laek.svg", src={"/images/laek.svg"})the build, against public/ (decision 0099)E0354
A quoted value an attribute cannot take: <slider min="abc">, rows="many", <button disabled="false"> (which ships a disabled button)the analyzer, from accepts (decision 0095)E0355
A value imported from a local .ts file, with or without its extension, which the built app does not includethe analyzer (decision 0097)E0356
A file outside the project, however the import that reaches it is writtenthe analyzer for a relative path; the refusals, from what TypeScript resolved, for every other way (decision 0097)E0356
A comment that turns type checking off, in any letter case, or a triple-slash reference however it is spaced, in a page or a project .ts or .d.ts filethe analyzer, and the refusals from what TypeScript honours (decision 0097)E0357
A value typed any used anywhere, whatever produced it (JSON.parse, a type alias, a package): read from, called, assigned, passed, returned, spread, destructured, given as a prop or shown in markupthe refusals, from what TypeScript resolved (decision 0097)E0358
The any keyword, the Function, CallableFunction and NewableFunction types and a call of one, eval and Function under any name or key, text given to setTimeout or setInterval, !, as unknown as, as never, a cast from unknown to a type parameter and let x!: T, in a page or a project .ts or .d.ts filethe analyzer from the text, and the refusals again from what TypeScript resolved, except !, as unknown as and let x!: T, which the text alone shows (decision 0097)E0358
declare (const, let, var, function, class, enum, module, global) and namespace, which name what does not exist when the page runsthe analyzer (decision 0097)E0359
A type error in a project's own .ts fileTypeScript, at that file's lineE0340 to E0349
An import of a file or package that does not existTypeScriptE0347
A value of the wrong type anywhere: a prop, an attribute, a word, a handler, a bindingTypeScript, through the script viewE0340
A name or field that does not existTypeScriptE0341
A required prop, argument or field not givenTypeScriptE0342
A value that may be missing: data not loaded yet, a signed-out user, an item read by position, a query keyTypeScript, with strict and noUncheckedIndexedAccessE0343
A key read from a route's query as if it were knownnoPropertyAccessFromIndexSignatureE0345
A switch that misses a case of a union, a function that does not always returnnoImplicitReturns, noFallthroughCasesInSwitchE0346
A comparison that is always false (tone === "dnager")TypeScriptE0348
An effect used where it does not exist, or without its permissionthe effects checksE0220 to E0223

Not caught when the app is built

These depend on data, the network or the person using the app, which the build cannot see. Each is handled when the page runs.

  • Business logic. A price computed wrongly, a rule applied to the wrong people, a form that accepts what it should not: the types are right and the behaviour is wrong. Tests catch these, not the compiler.
  • What a server sends. server.get<Post[]>("/posts") says what the page expects; nothing checks that the server agrees. A failed request is the loaded state's error.
  • Paths built from data. href={post.link}, `navigate(/post/${id}), "/post/" + id, a path held in a let or in a const inside a function, and a parameter are checked by the router when they are followed (the not-found screen), and their scheme by the runtime (decision 0040). A path written as text where it is used, or held in a top-level const of the script (or in a property of one written as const`), is checked when the app is built. Names are resolved by scope: a parameter, a local or a list's item with the same name as a top-level const is not that const.
  • A repeated key in a list. Keys come from data.
  • Loaded state that failed. TypeScript forces a page to handle "no data yet", not "failed". Decision 0098 proposes a union of loaded state's statuses, and a <match> element that makes a missing case in markup an error. Neither is built.
  • **A type guard that lies, and a cast from unknown.** function isPost(x: unknown): x is Post { return true; } is trusted where it is used, and so is data as Post where data is unknown; the guard's body, and the check before the cast, are what must be right. A cast from unknown to a type parameter is refused (above), so a generic function cannot hide one.

How it runs

duolith check (and build and dev) make each file's script view in Rust and send them to a small Node program, packages/checker, which builds one TypeScript program for the whole project with the language server's own language plugin. duolith dev keeps the checker running between rebuilds. It keeps every unchanged parsed file, and since nothing imports a page (E0117), when only pages changed it checks only those and keeps the other pages' errors from last time; a change to a component or a .ts file checks every file again. Each rebuild still makes a new TypeScript program, which is most of its time: on examples/gallery an edit to one page takes about 1.4 s to rebuild and check. Without Node 22.18 or later the check fails (E0350), as it does without the checker's packages (E0351). A checker that stops is never kept: one that duolith dev kept running and that has stopped since is started once more in the same check, and one that stops on its first request is not started again in that check, since it would only stop again. The next rebuild starts a fresh one, so duolith dev recovers once whatever stopped it is gone; one check starts at most two checkers, so a checker that always stops costs each rebuild one start and never loops. Its message says what it printed is above, or that it printed nothing. A checker that stops, gives an answer Duolith cannot read, leaves out a file it was asked to check, or does not answer within 180 seconds (DUOLITH_CHECK_TIMEOUT sets another) fails the check with E0352, and duolith dev shows that error like any other. DUOLITH_NODE and DUOLITH_CHECKER can name another Node or checker; Duolith prints a warning once in each run that uses them. Decision 0096 has the details.