Types
| Rook | Values | In JS |
|---|---|---|
number |
numbers | number |
bigint |
whole numbers of any size, 10n |
bigint |
byte |
a number from 0 to 255 | number |
string |
strings | string |
bool |
true, false |
boolean |
any |
anything, unchecked | — |
void |
no value: Promise<void> |
undefined |
never |
no value at all: a function that never ends | — |
error |
an error or null |
Error or null |
T[] |
an array | Array |
byte[] |
bytes | Uint8Array |
float64[], ... |
numbers of a fixed size | Float64Array, ... |
queue T |
values in order, taken out at both ends | $$deque |
?T |
a value of type T or null |
a value or null |
func(A, B) R |
a function | a function |
(a A) => R |
the same function type, written as an arrow | a function |
comp(a A) |
a component, which a tag takes from a value | a function |
A | B |
a value of type A or of type B |
a value |
"all", 42 |
exactly that value | a value |
{ x number } |
an object with these fields | an object |
{ [string]: T } |
an object used as a map: any key, values T |
an object |
| a class name | an instance of the class | an instance |
| an interface | any value with the needed fields and methods | — |
The type goes after the name, without a colon: x number, xs string[], cb func(number) bool,
user ?User.
Typing is structural, as in TypeScript: a value fits a type if it has all the needed fields and methods of the needed types.
- An array is written after the type of its elements, as in TypeScript:
string[],number[][],Map<string, User>[].[]belongs to the type just before it, so a type written with a word or a sign before it takes[]inside:?string[]is an array ornull,func() number[]gives an array,queue string[]holds arrays. An array of such a type puts it in parentheses:(?string)[]is an array of nullable strings,(func() number)[]an array of functions,(string | number)[]an array of both. - A function type as an arrow,
(paths string[]) => Shape, is the same asfunc(string[]) Shape; the names of the parameters only document them, and=> voidmeans no result. Parentheses with one type and no arrow still group:(string | number)[]. - The parameters of a function type may have names, which only document them; as in Go, if one
has a name, all have, so
func(a, b number) numbertakes two numbers. The rest of the arguments is last,func(string, ...any[]). voidis the value of a Promise without one,Promise<void>, and of a callback whose result is not used. As the result of a function it is no result:close() voidisclose(). A function whose result in a.d.tsisanyorvoid | Tmay end withoutreturn, and a parameter that takesvoidmay be left out at the end, as theresolve()of aPromise<void>.neveris the result of a function that never ends: it throws or exits, asprocess.exit. Its body must not reach its end, and the code after a call of it is not reached, so the call narrows types asthrowdoes (section 12).- An object used as a map,
{ [string]: number }, has any keys with values of that type; the key isstringornumber. An object literal or another object fits it if all its fields do.scores["ann"]andscores[name]are anumber, anddelete scores[name]removes a key. - There is no
map[K]Vof Go: an object with string keys is the map that JS code and JSON use, written as a literal, and aMap<K, V>of JS, typed from its lib, takes keys of any type. A third map with its own syntax would only have to be converted to them.
bigint
let big = 2n ** 64n // 18446744073709551616n
let zero bigint // 0n
const third = big / 3n // the fraction is dropped
const n = Number(big) + 0.5 // a number again
bigint holds whole numbers of any size, as in JS. A literal ends with n: 10n, 0xffn,
1_000n; it has no fraction or exponent. The zero value is 0n.
- It does not mix with numbers in arithmetic:
big + 1is an error, since JS throws a TypeError there. One of them is converted:big + 1n,BigInt(n),Number(b). - Comparisons:
<,>,<=and>=work between a bigint and a number, as in JS.==between them is an error: it compiles to===, which is alwaysfalsefor the two. -b,~b,b++and the bit operators work;+band>>>are errors, as JS throws there.typeof bis"bigint"and narrows anumber | bigint. A bigint goes into markup as text and to a goroutine as a copy;JSON.stringifycannot write one (JS throws).
byte[]
let header byte[] = [0x89, 0x50, 0x4e, 0x47]
let empty byte[]
const bytes = byte[]("rook")
const text = string(bytes)
let header = new Uint8Array([0x89, 0x50, 0x4e, 0x47])
let empty = new Uint8Array()
const bytes = new TextEncoder().encode('rook')
const text = new TextDecoder().decode(bytes)
byte[] is a Uint8Array, as a byte slice in Go, and byte is a number from 0 to 255 (the
range is not checked, as for other numbers). data[i] reads and writes a byte, and the methods
are those of Uint8Array: subarray, slice, set, and no push, since its length is fixed.
- A list of numbers where a
byte[]is expected becomes one; the zero value is an emptyUint8Array. - Text and bytes convert as in Go, in UTF-8:
byte[]("text")andstring(bytes). They are the only conversions written with a type:string(65)is an error (in Go it would be"A"), and other values useString(x)or a template string. A program that declares a typebyteor a valuestringuses its own. - A
byte[]goes to a goroutine as a copy, or without one withtransfer(data).
Typed arrays
const samples = make(float32[], 4)
let weights float64[] = [0.25, 0.5, 0.25]
let ids uint32[]
const counts = make(int64[], 8)
const field = make(float64[], 1_000_000, shared)
const samples = new Float32Array(4)
let weights = new Float64Array([0.25, 0.5, 0.25])
let ids = new Uint32Array()
const counts = new BigInt64Array(8)
const field = new Float64Array($$shared(8 * 1_000_000))
The typed arrays of JS are written as arrays of the number types of Go, as byte[] is: their lengths are fixed, and
their elements are numbers of a fixed size, stored in a buffer without boxes.
| Rook | JS | Elements |
|---|---|---|
int8[] |
Int8Array |
number, from -128 to 127 |
uint8[] |
Uint8Array |
number, the same as byte |
int16[] |
Int16Array |
number |
uint16[] |
Uint16Array |
number |
int32[] |
Int32Array |
number |
uint32[] |
Uint32Array |
number |
float32[] |
Float32Array |
number |
float64[] |
Float64Array |
number |
int64[] |
BigInt64Array |
bigint |
uint64[] |
BigUint64Array |
bigint |
- The element types are other names of
number, and ofbigintforint64anduint64, asbyteis:const x float64 = data[0]. The ranges are not checked, as for other numbers; a value is converted to the element when it is stored, as in JS.uint8[]isbyte[]. - The JS names are the same types: a
Float64Arrayof a library goes where afloat64[]is expected.Uint8ClampedArray, whose values stop at 0 and 255 (the pixels of a canvas), has no name in Go and keeps its own. make(float64[], n)makes a typed array ofnzeros, asmakedoes in Go. A length is only for typed arrays: a list,number[], starts empty and grows.make(float64[])is an empty one, asmakeof any type is its value ("make" below).make(float64[], n, shared)puts it on aSharedArrayBuffer, which the workers ofgo forwrite into without copies. A page has one only with cross-origin isolation (the headersCross-Origin-Opener-Policy: same-originandCross-Origin-Embedder-Policy: require-corp); elsewheremakethrows an error that says so. Node always has it.- A list where a typed array is expected becomes one, as for
byte[]; the zero value is an empty one. The methods are those of the typed arrays:subarray,slice,set,fill, and nopush. - A program that declares a type
float64or another of these names uses its own:float64[]is then an array of it.
Queues
Experimental: may change between releases; see the status at the top.
const jobs = queue<string>(["build", "test"])
jobs.push("deploy") // at the end
jobs.unshift("lint") // at the start
const next = jobs.shift() // ?string, "lint"
const last = jobs.pop() // ?string, "deploy"
console.log(jobs.length, jobs.at(0), jobs.at(-1))
for job in jobs {
console.log(job)
}
let waiting queue number // an empty queue
const jobs = new $$deque(['build', 'test'])
jobs.push('deploy')
jobs.unshift('lint')
const next = jobs.shift()
const last = jobs.pop()
// ...
let waiting = new $$deque()
queue T keeps values of type T in order, and they go in and out at both ends. It has the
methods of an array that a queue needs, but shift() and unshift() do not move the other values,
as they do in an array, so taking the first of 100 000 values costs as much as taking the first of
ten. queue<T>() makes an empty queue, and queue<T>(items) one with the values of an array or of
another iterable, which it copies.
- The methods:
push(...items)andunshift(...items)add values at the end and at the start and give the new length;shift()andpop()take one out at the start and at the end;at(i)gives the value at a position, from the end if it is negative,at(-1)is the last;lengthis the number of values andclear()removes them all.shift(),pop()andat(i)give a?T:nullfor an empty queue or a position outside it, where an array givesundefined. There is noq[i], normaporfilter:[...q]makes an array of the values. for v in qgoes over the values from the start, without taking them out. A queue has no keys, sofor i, v in qis an error.- Only a queue is a queue: a
T[]is not aqueue T, nor the other way round. Aqueue numbergoes where aqueue ?numberis expected, as an array does, and a queue goes where an interface with its members is expected,{ length number }. queueis a name elsewhere: it is a type only before the type of its values,queue number, and makes a queue only before<T>(. So a variable may be calledqueue, andqueue < ncompares it.queue<number>as a type is an error that says to writequeue number.- The zero value is an empty queue, a new one for each variable and field, as
[]is for an array; a closedchan queue Tgives an empty queue too. - In JS a queue is an instance of the class
$$deque, which the module gets when its code uses queues: the values are a ring in an array, copied into one twice as large when it is full and into one half as large when it is mostly empty. Its fields are data, so a queue goes to another thread as a copy, if its values can be copied, and is a queue there too. TypeScript code sees its members in the.d.ts. The values of a channel and the goroutines that wait for it are kept in such queues as well.
Type declarations
type ID string
type Handler func(string) bool
type Pair { first, second number }
type gives a type another name: ID and string are interchangeable (in Go they would be
different types). The shape of objects is usually described with interfaces (section 9).
Union and literal types
type Filter "all" | "active" | "done"
func show(value string | number) string {
if typeof value == "string" {
return value.toUpperCase()
}
return value.toFixed(2) // here value is already a number
}
A | Bis a value of one of the types. Parentheses group:(string | number)[],?(A | B).?applies to the nearest type, andfunc() A | Bis a function that returns a union.- A literal type
"all",42ortrueallows only that value. A union of literals catches typos:filter = "activ"andfilter == "activ"are errors. - A member of a union can be used if every type has it:
string | numberhastoString()but notlength. To get to the rest, the type is narrowed (section 12). - A literal in code gets a literal type only where one is expected:
let f = "all"is astring, andlet f Filter = "all"is"all". - Branches of
?:, array items and the differentreturns of a function without a declared result give a union when their types differ:[1, "a"]is(number | string)[]. - Unions and literal types have no zero value:
let f Filtermust be initialized. - A field by a key whose value is known:
point["x"], orpoint[axis]withaxis "x" | "y", is the field (or the union of the fields) of the object. A key that is not a field is an error.
Tagged unions
Experimental: may change between releases; see the status at the top.
interface Pickup { kind "pickup"; shop string }
interface Courier { kind "courier"; address string; floor ?number }
type Delivery Pickup | Courier
interface Order { id number; delivery Delivery }
func where(order Order) string {
if order.delivery.kind == "courier" {
return order.delivery.address // here order.delivery is a Courier
}
return order.delivery.shop // and here a Pickup
}
where({ id: 1, delivery: { kind: "pickup", shop: "Main st." } })
- A tag is a field that every member of a union has, with a literal type: a string, a number
or a union of literals (
state "new" | "edited"). A union may have several tags. Interfaces and classes with such a field work the same way. - Comparing a tag narrows the value it belongs to: in
if d.kind == "courier"the valuedis aCourier, and inelsethe other members.!=,!,&&,||, a branch that returns,switch d.kindwith itscaseanddefault, and{if}and{switch}of markup narrow as in section 12. - An object literal where a union is expected is checked as the member that its tag chooses:
{ kind: "pickup", shop: "..." }is aPickup, with the usual check of its fields. A tag of no member is an error:"plane" is not a kind of Delivery: write "pickup" or "courier". decode<Delivery>(text)checks such a union when the program runs (section 7), and its result narrows too.- There is no check that a
switchcovers every kind: aswitchwithoutdefaultthat leaves a kind out is neither an error nor a warning. - Nothing changes in JS: a tag is an ordinary field, and its comparison an ordinary
===.
Generics
Type parameters go in angle brackets after the name, as in TypeScript, and a constraint follows its parameter, as in Go:
func first<T any>(xs T[]) ?T {
return xs.length > 0 ? xs[0] : null
}
interface Box<T> {
value T
}
type Pair<A, B any> { first A; second B }
class Stack<T> {
private items T[]
push(item T) { this.items.push(item) }
pop() ?T { return this.items.pop() ?? null }
}
const n = first([1, 2, 3]) // ?number
let b Box<string> = { value: "a" }
let s Stack<number> = new Stack()
- A constraint goes after the name:
<T Named>meansTmust fitNamed, and values of typeThave the members ofNamed.anymeans no constraint, and thenThas no members. Several names in a row share one constraint:<K, V any>. Interfaces, classes andtypemay leave the constraint out:interface Box<T>. - Type arguments of a type are written after it:
Box<number>,Pair<string, ?number>. In calls they are inferred from the arguments, and failing that, from the expected type:let xs number[] = empty(). A call may also give them,empty<number>(),first<string>(xs): types in<>right before(are type arguments, and anything else is a comparison, soa < b && c > (d)stays two of them.newtakes none:new Stack<number>()is an error, and the variable gets the type,let s Stack<number> = new Stack(). If there is nothing to infer from, it is an error:let s = new Stack(). - Inside a function,
Tis a type of its own:return 1in a function with the resultTis an error.Thas no zero value, butmake(T)gives the value of the type of each call ("make" below). - A type can refer to itself:
interface Tree<T> { value T; children Tree<T>[] }. Box<number>andBox<string>are different types, and so areStack<number>andStack<string>.- A generic class cannot be extended yet: the base after
extendsis a value, as in JS, soextends Stack<number>cannot be written. Methods with type parameters of their own (map<U any>(...)) are not supported yet either. - In JS, generics are erased, as in TypeScript.
make
make(T) is the value of a type, which the compiler computes, so that no type is left in the JS:
interface File {
name string
size number
type ?string
}
type MyNumber number
const a = make(File) // { name: "", size: 0 }
const b = make(File[]) // []
const c = make(number) // 0
const d = make(MyNumber) // 0
const a = { name: '', size: 0 }
const b = []
const c = 0
const d = 0
- The value of a type with a zero value is that zero value:
0,0n,"",false,[], an empty typed array or queue, a closed channel,nullof?Tandany. An interface or an object type is an object of its fields, each with its own value; a field that may be missing,?Torany, is left out. A literal type is its literal:make(Circle)withkind "circle"gives{ kind: "circle", r: 0 }.MapandSetare empty,new Map(). A class of Rook whose constructor takes nothing isnew Cart(). - No value: a union, a function, an interface with methods, a type that has itself as a field
(
next Node;next ?Nodeis fine), a class whose constructor takes arguments and a class of a library (new Date()would be the time) are errors that say why. - Each
makeis a new value: twomake(File)are two objects. makeis a word here, as in Go: a program that declares a valuemakegets an error atmake(...)that asks to rename it.make(x, 1), which is no type, is a call.
In a generic function, make(T) is the value of the type that each call gives T, and so is the
type that decode<T>(x) checks against (section 7). The compiler finds the types of the calls in
the module:
func create<T>() T {
return make(T)
}
const num = create<number>()
const str = create<string>()
function create($$Tmake) {
return $$Tmake()
}
const num = create(() => 0)
const str = create(() => '')
- Called with one type, the function gets the value in its body:
create<number>()alone makesfunction create() { return 0; }, and the call passes nothing. - Called with several, or exported, it takes what its type parameters give before its own
parameters: for
make(T)a function that makes the value,$$Tmake, and fordecode<T>the type,$$Ttype. A function, not a value, so that eachmake(T)is a new object, as it is without generics. Other modules see these parameters too, and so does the.d.ts:create<T>($$Tmake: () => T): T. - Never called, it is left out of the JS with a warning: nothing says what T is.
- A function that passes T on needs it too:
func pair<T>() T[] { return [create<T>(), create<T>()] }passes its$$Tmaketocreate, or its one type. - A function whose body has no
make(T)ordecode<T>is as before: its types are erased, and nothing is passed. - Such a function cannot be a value,
const f = create, since a value has no T: it is called,() => create<number>(). T must come from the call,create<number>(), or from the arguments and the expected type. - Only the type parameters of
funcgive values:make(T)with T of a class or a method is an error. - With
rook build --no-check, without the types,makewrites only what the type as written shows (0,"",[]); others areundefined.
null and null safety
The language has one "empty" value, null; Rook has no undefined. An ordinary ==
compiles to ===, but a comparison with null stays loose: x == null → x == null. So it also
catches undefined coming from JS code.
null can be assigned only to ?T, error and any. To use a field or a method of a value of
type ?T, the type must first be narrowed:
func findUser(id number) ?User { ... }
const u = findUser(1)
console.log(u.name) // error: u may be null
console.log(u?.name) // fine: the type is ?string
console.log(u?.name ?? "anonymous") // fine: the type is string
if u != null {
console.log(u.name) // here u is a User
}
if u == null {
return
}
console.log(u.name) // and here: on null the function has returned
- Narrowing works for local variables, parameters and paths of fields from them: in
if user.boss != nullthe valueuser.boss.namecan be read (section 12). A field ofthis(this.user) is first put into aconst. erroralways allowsnull; there is no need to write?error. A function that gets an error already checked takesError, which does not:func describe(err Error) string.x!takes a value not to benull, as in TypeScript:env.PORT!is astring. Nothing is checked at runtime, so a wrong!fails where the value is used; a check or??is safer. The!is right after the value, so!xbefore one stays a negation.xs[i]has the typeT, not?T: the compiler does not catch indexes out of bounds (nor does TypeScript by default).- Values of type
any, including everything imported from JS modules without types, are not checked.