Type checking
The compiler checks types before generating JS; a program with type errors does not compile
(rook build --no-check skips the check).
hello.rk:4:17: error: cannot use ?User as User: it may be null, check it first
hello.rk:7:13: error: "u" may be null: check it with "if u != null" or use "?."
hello.rk:9:11: error: cannot add string and number: use a template string, e.g. `${a}${b}`
What is checked
- The types of values in declarations, assignments, arguments and
return; the number of arguments and results;missing returnif a function with a result can reach the end of its body. - Null safety: using fields and methods of
?T, passing?TwhereTis expected. - The conditions of
if/for/?:and the operands of&&,||,!must bebool. - Operators:
+for two numbers or two strings, arithmetic only for numbers,==only for comparable types. - Names: unknown variables and types, assignment to constants and loop variables,
_as a value. - Classes:
private/protectedvisibility, the constructor's arguments, asuper(...)call in the constructor of a subclass, compatible overridden methods,implements, fields without a zero value that are not assigned. - Object literals: missing fields, extra fields (a likely typo), the types of fields.
Narrowing
The type of a local variable or a parameter narrows from ?T to T, and so does the type of a
path of fields from one, order.delivery (see below):
- inside
if x != null { ... }and in the branches of?:; - after
if x == null { return }(andthrow,break,continue, or a call of a function whose result isnever, asprocess.exit(1)); - on the right side of
x != null && x.okandx == null || x.ok; - in the body of the loop
for x != null { ... }; - after an assignment of a value that cannot be
null.
Unions narrow the same way:
typeof x == "string"keeps the members for whichtypeofgives"string", and!=the rest; foranyit narrows tostring,numberorbool;x instanceof Pointkeeps the instances ofPointand removes them in the false branch;filter == "all"narrows a union of literals to"all", and!=removes"all";- in
switch filter { case "active": ... }, in each branchfilteris the literals of itscase, and indefaultthose that matched nocase; - comparing a tag,
d.kind == "courier"orswitch d.kind, keeps the members of a union with this tag (section 3, Tagged unions).
An assignment to a variable ends its narrowing. In a loop, variables that change in it are not narrowed. In a closure, narrowing is kept only for constants and variables that are never reassigned.
Paths. A path is a chain of .field from a local variable, a parameter, state, derived
or a const of the module: order.delivery, response.data.user. It narrows the same ways as a
variable, without an intermediate const:
- an index
a[i], a call and?.end a path:users[0].bossis not narrowed; - only data fields narrow, not getters and methods: a getter may give another value each time;
- an assignment to the path or to its start ends its narrowing, and so does one to its tag, which
may make it another member of the union:
order = ...,order.delivery = ...andorder.delivery.kind = ...end that oforder.delivery, butorder.delivery.floor = 2does not. A tag of a variable is the same:d.kind = ...ends the narrowing ofd; - in a loop, paths that it assigns are not narrowed; in a closure, the narrowing of a path is kept when its variable is a constant or is never reassigned.
A call of a function that changes the object does not end the narrowing of its paths, as in
TypeScript: after if order.delivery.kind == "courier" { reset(order) } the compiler still
considers order.delivery a Courier. This is a deliberate trade-off for convenience: a function
that replaces a field of an object it is given is rare, and checking every call would undo the
narrowing almost everywhere.
Type inference
let x = valuegets the type of the value;nulland[]without a declared type are errors.- The parameters of an arrow function take their types from the context:
xs.map(x => x * 2),apply(n => n > 0). The result of an arrow function is inferred from its body. - The type of array items is the common type of all of them:
[1, null]is(?number)[].
Built-in JS types
By default, the compiler uses TypeScript's lib files (ES2025 and DOM) and the global @types
packages available to the project. For example, @types/node provides process and Buffer:
document,window,fetch,Promise,Map,Set,Date,URL,Object… are typed:document.getElementById("app")is a?HTMLElement,new Map()withlet m Map<string, number>is aMap<string, number>, andm.get(k)is a?number;<input>creates anHTMLInputElementwith all the members fromHTMLElementTagNameMap;eventinonClickis aPointerEvent, inonKeyDownaKeyboardEvent(fromHTMLElementEventMap), andevent.currentTargetis the element itself.event.targetis a?EventTarget, as in TypeScript;window.addEventListener("keydown", event => ...)and the correspondingremoveEventListenerinferKeyboardEventfromWindowEventMap. Custom event names use the overload for arbitrary strings;x instanceof HTMLInputElementnarrows the type, although in lib.dom it is a constructor, not a class;- strings, numbers and arrays have all the methods of
String,NumberandArray<T>.
TypeScript supplies the signatures and overloads for console, Math, JSON, timers and
the methods of strings, numbers and arrays. Results that can be undefined in TypeScript, such as
find, pop and at, are nullable in Rook. Rook provides its own declarations for the
predeclared functions and the Error class of its error type.
The playground uses standard-library and DOM types generated from TypeScript declarations by
npm run browser:types. The browser loads a compact data set that includes document, fetch,
Map, Promise, timers and streams. Large interfaces retain a selected set of members. Results
whose shape is unknown, such as Response.json(), have type unknown and can be checked with
decode<T>.
The types from imported .rk modules are checked: the compiler reads those modules itself. The
types of other imports come from TypeScript declarations (section 10).