# 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 return` if a function with a result can reach the end of its body.
- Null safety: using fields and methods of `?T`, passing `?T` where `T` is expected.
- The conditions of `if`/`for`/`?:` and the operands of `&&`, `||`, `!` must be `bool`.
- 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`/`protected` visibility, the constructor's arguments, a `super(...)` 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 }` (and `throw`, `break`, `continue`, or a call of a function whose
  result is `never`, as `process.exit(1)`);
- on the right side of `x != null && x.ok` and `x == 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 which `typeof` gives `"string"`, and `!=` the rest;
  for `any` it narrows to `string`, `number` or `bool`;
- `x instanceof Point` keeps the instances of `Point` and 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 branch `filter` is the literals of its `case`,
  and in `default` those that matched no `case`;
- comparing a tag, `d.kind == "courier"` or `switch 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].boss` is 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 = ...` and
  `order.delivery.kind = ...` end that of `order.delivery`, but `order.delivery.floor = 2` does
  not. A tag of a variable is the same: `d.kind = ...` ends the narrowing of `d`;
- 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 = value` gets the type of the value; `null` and `[]` 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()` with
  `let m Map<string, number>` is a `Map<string, number>`, and `m.get(k)` is a `?number`;
- `<input>` creates an `HTMLInputElement` with all the members from `HTMLElementTagNameMap`;
- `event` in `onClick` is a `PointerEvent`, in `onKeyDown` a `KeyboardEvent` (from
  `HTMLElementEventMap`), and `event.currentTarget` is the element itself. `event.target` is a
  `?EventTarget`, as in TypeScript;
- `window.addEventListener("keydown", event => ...)` and the corresponding
  `removeEventListener` infer `KeyboardEvent` from `WindowEventMap`. Custom event names use
  the overload for arbitrary strings;
- `x instanceof HTMLInputElement` narrows the type, although in lib.dom it is a constructor, not a
  class;
- strings, numbers and arrays have all the methods of `String`, `Number` and `Array<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).

