The language
The language
What can be written today, and what it becomes. Everything on this page is run by the tests
(packages/compiler/test); what is planned and not built is at the end, under « Not in the language yet », and
what is taken on trust is in Known limits.
A file ends in .sts and holds declarations: import, extern, type, function, const. Nothing runs at the
top of a file; a program starts in a function, by convention export function main(args: string[]). A value at
the top is written, not computed: a record, an array, Map.from([…]), Set.from([…]), a function.
type Line = { label: string, quantity: number, unitPrice: number }
type Status = "draft" | "sent" | "paid" | "cancelled"
export type Invoice = { id: string, customer: string, status: Status, lines: Line[], paidAt?: string }
export function total(invoice: Invoice): number {
invoice.lines.sum(line => line.quantity * line.unitPrice)
}
export function parseInvoice(json: string): Result<Invoice, JsonError | ParseError> {
Invoice.parse(JSON.parse(json)?)
}
#What has no word
any, a cast (as), null, undefined, throw, try, catch, class, this, new, typeof, instanceof,
in, delete, var, switch, enum. Each is refused where it is written, with what to write
instead. There is no declaration without a value, no overload, no default for a parameter, no computed key, no getter.
from, of, type, resource and end are words only where the grammar asks for them: elsewhere they are names. A
property may be named with any word, of the language or of JavaScript: { type: "a", mut: true, class: "b" },
node.type, entry.default. A word of JavaScript that has no meaning here is the name of a property and of nothing
else.
#Types
| Type | Notes |
|---|---|
string, number, bigint, boolean | JavaScript's own. A number that is written holds what is written: 9007199254740993 and 1e999 are refused (number-not-held), since the first would be another number and the second none. See « Numbers that are not numbers » |
"draft", 3, true | A written value is a type |
{ name: string, nick?: string } | A record. Closed: it holds the properties its type names and no other, so a record with one more property does not fit. Reading nick gives an Option<string>, and it is written from one too: { name, nick: maybe } has a nick when maybe holds a value |
T[] | An array. Read-only: [...values, one] makes another |
mut T[], mut Map<K, V>, mut { … } | A value that can be changed, as the type of a parameter or of what a function gives back. See « Values that can be changed » |
(a: A, b: B) => R | A function. It fits where another is asked for when it takes at least what the other takes and gives at most what the other gives |
A | B | A union, when something tells its members apart as the program runs: they differ by their kind (a text, a number, an array, a record), or they are records with a property that holds a different written value in each (kind: "circle") |
Option<T> | Some(value) or None |
Result<T, E> | Ok(value) or Err(error) |
Map<K, V>, Set<T> | Collections found by key. A key is a text, a number, a bigint or a boolean. They are not changed in place: set, add and without give another one. A Map whose keys are texts is a dictionary: what an object of the outside with keys not known in advance is read as |
Regex | A regular expression, JavaScript's. Regex.of("[0-9]+", "i") is written where it is made, tried where the program is compiled, and may stand at the top of a file; Regex.from(text, flags) takes any text and gives an Option |
Markup | An element: what a program shows. See « Elements » |
Promise<T> | What an async function gives. It never rejects: what may fail gives a Promise<Result<T, E>> |
| a type of the outside | Declared in an extern (type Server). The language holds its values and hands them back, and never looks into them |
unknown | What came from outside and was not read yet. The only thing to do with it is Type.parse(value) |
void | What a function that gives nothing gives: nothing. Whatever its body ends on or returns is worked out and left, and no value of this type is named, compared or read |
type Name = … gives a type a name; type Pair<A, B> = { first: A, second: B } takes parameters. A type may name
itself inside a record or an array (type Tree = { value: number, children: Tree[] }).
Types are compared by their shape, not by their name. Nothing is assumed where the answer is not known: a value of one type is never taken for another to make a program pass.
#Values and names
const tax = 0.2 // keeps its value
let sum = 0 // may be given another: sum = sum + 1
const user = { name: "Ada", age: 36 }
const older = { ...user, age: 37 } // a new record; `user` is as it was
const all = [...values, 4]
const text = `${user.name} is ${user.age}`
- A name is declared with its value, above the line that uses it, and once: an inner block does not declare a name that is already visible. A parameter may hide a name declared around its function.
total += 1istotal = total + 1; so are-=,*=,/=,%=, on aletand on a property of a record that can be changed.- A
letis not used by a function written inside the one that declares it: copy it into aconstfirst. - A template takes texts, numbers, bigints and booleans.
+joins two texts or adds two numbers, never one of each. ==and!=compare two texts, two numbers, two bigints or two booleans;<,<=,>,>=order two numbers, two bigints or two texts.- There is no conditional operator:
ifis an expression (const sign = if (n < 0) "-" else "+"). Where nothing reads its value, anifor amatchis a statement, and so are its branches: they need not give one type.
#Values that can be changed
Every value is read-only, unless the name it is declared under says mut:
const mut basket: Item[] = []
basket.push(pen)
const mut counts: Map<string, number> = Map.from([])
counts.set("pen", 1)
const mut state = { sum: 0, count: 0 }
state.sum = state.sum + 5
What can be changed is an array, a record, a Map or a Set. It has one owner: its name. Everything else follows
from that.
| It is made where it is named | From a value written there ([…], { … }, Map.from, Set.from) or from a function that gives one back (function make(): mut number[]). A value that has other names is copied first: const mut mine = [...theirs] |
| It is lent to be changed | The function asks: function restock(mut counts: Map<string, number>, item: Item). The call says so too: restock(mut stock, pen). Who reads the call knows stock may change. The function may change it and lend it on; it may not keep it, give it away or give it back |
| It is read as any value | basket.length, basket[0], basket.map(…), [...basket] |
| It is lent to be read | To a function of the program that only reads the parameter: total(basket). Nothing is written for it: the compiler finds that total looks at its parameter and keeps nothing of it. The owner goes on after the call. A resource is never lent to be read: a function that takes one takes it for good |
| It is given away for good | Anywhere else its name is written, the value is handed over, and the name is dead after: const order: Item[] = basket, return basket, { items: basket }, keep(basket) where keep may keep what it is given. Whoever receives it holds a value that nobody can change any more. To keep using it, give a copy: keep([...basket]) |
So a read-only value never changes under the one who holds it: there is no read-only view of something its maker still changes.
A function only reads a parameter when every place its name stands is one where the value is looked at: a
property read, a method of the language, a position, a loop, a copy by spread, an argument to a function that only
reads it too. It keeps it when it gives it back, names it, puts it in a record or an array, lets a function written
in place name it, hands it to a function held in a value, or is async. This is found from the body, for the
functions declared at the top of a file, and goes with them through an import.
#Parts that a record owns
type State = { source: string, at: number, mut tokens: Token[], mut seen: Map<string, number> }
const mut state: State = { source, at: 0, tokens: [], seen: Map.from([]) }
state.tokens.push(token)
state.at += 1
note(mut state.tokens, "…")
A property written mut name: Type is a part the record owns. Under a name declared with mut, the part is changed
in place through the record, read there, and lent on its own. It is made where the record is written, or given by
its owner (not-fresh otherwise); it is not handed out as a value, which would be a second name for it (part-of):
[...state.tokens] gives a copy. When the record is given away, its parts go with it, and nobody changes them any
more. In a record that nobody can change, mut on a property says nothing: the part is read as any property.
A spread of a record that owns parts copies the record, not the parts: { ...state } is refused (part-of) until
each part is written again with a copy, { ...state, tokens: [...state.tokens] }. And a record is lent to be read
only to a function whose parameter says the same parts are owned: to any other it is given, and its name is dead
after.
#Functions handed to a method of the language
const mut seen: number[] = []
let total = 0
const doubled = values.map(value => {
seen.push(value)
total += value
value * 2
})
A function written where a method of the language asks for one (map, filter, find, reduce, sortBy…) is
called before the method ends and is not kept. It may read and change the values of the function around it, and
give another value to its lets. It may not give a value away, since it may run several times; and what the method
was called on is not changed while it runs. A function that is kept, or handed to a function of the program, still
names no value that can be changed (mut-captured) and no let (let-captured). So does one handed over as a
value: later.push(() => …), the starting value of a reduce.
#A value that several parts of a program share
function counter(): () => number {
const count = Cell.of(0)
() => {
count.set(count.get() + 1)
count.get()
}
}
A Cell<T> holds one value, and everyone who holds the cell sees the value it holds now: get() reads it, set(value)
puts another one in. It is what a cache, a store or a counter that outlives a call is made of, and the one thing a
function that is kept may change.
- What it holds is read-only, as any value: a
Cell<number[]>is given another array, its array is not pushed to. Whoever read the value before asetstill holds what they read. A value that can be changed goes into a cell by being given away. - Its type says it: nothing changes behind a type that does not say
mutorCell. ACell<"a">is not aCell<string>. - It is made in a function, never at the top of a file: a program has no state that nobody was handed.
- It is not a key, not part of a union, not written as JSON, and does not cross the boundary with the outside.
- Two
asyncfunctions that share a cell see each other's changes between twoawaits. Each value read is whole; the order of the changes is the program's to get right. - A table kept in a cell is copied at each change:
seen.set(seen.get().add(value)).
What is refused, with the name of the rule:
used-after-given: a name used after its value was given away. In one branch of anifor one arm of amatch, it is gone after the wholeiformatch.given-in-loop: a value given away inside a loop that it was declared outside of.mut-captured: a function that may be kept, and that names a value that can be changed. Hand it over as a parameter.not-fresh:const mutgiven a value that may have other names.not-yours: a parameter that was lent, given away or given back.lent-twice: one value lent twice to one call.changed-while-read: an array changed while aforgoes through it.mut-inside:mutin the type of an element or of a type argument. An array holds read-only values; a record may own parts, marked on the property.mut-across-await: anasyncfunction that takes a value to change.- A value that can be changed is asked for exactly: a
mut string[]is not amut (string | number)[].
On a name declared with mut:
| an array | push, pop() (an Option), set(position, value) (says whether there was an element there: a position past the end is not written), insert(position, value) (before that position; past the end, it is put last), truncate(length) (keeps the first elements; never makes the array longer), clear(), reverse(), sortBy(f); and everything that reads |
a Map | set(key, value), delete(key), clear(); and everything that reads. set changes the map, where on a read-only map it gives another one |
a Set | add, delete, clear() |
| a record | name.property = value, for a property that is always there |
let mut may be given another value that can be changed, and the name is alive again.
#Resources
A resource is a value that must be ended: a transaction, a lock, a file that is open.
export resource Transaction { entries: string[] } end rollback
export function begin(): Transaction { { entries: [] } }
export function debit(mut tx: Transaction, account: string, cents: number) { … }
export function commit(tx: Transaction): string[] { … }
export function rollback(tx: Transaction) { … }
export function transfer(from: string, to: string, cents: number): Result<string[], "nothing-to-move"> {
const tx = begin()
debit(mut tx, from, cents)
if (cents <= 0) return Err("nothing-to-move") // rolled back here
credit(mut tx, to, cents)
Ok(commit(tx)) // given away: any use of `tx` after this is refused
}
Whoever holds a resource gives it to a function that takes one, or the function named after end is called when
the scope of its name ends: at the end of the block, on return, on the early return of ?, on break and
continue. No line is written for the paths that fail, and none can be forgotten.
- A resource has one owner, as a value that can be changed: it is lent with
mutto be changed, given away by writing its name anywhere else, and its name is dead after. - It is held by a name declared with
const, taken as a parameter (tx: Transaction: the function takes it for good, and ends it if it does not give it on) or given back by a function. It is not kept inside another value, in anOptionor aResult, nor dropped (resource-inside,resource-kept). - Only the file that declares it makes one, reads and writes what it holds, and ends it without its function
(
resource-private). There, naming what it holds with its type ends it:const written: { entries: string[] } = tx. That is howcommitandrollbackthemselves are written. - The function that ends it takes one and gives nothing, and is exported with it; a file that holds one imports it
(
needs-ender). - Between a resource handed to a call and the call, nothing leaves the function:
consume(tx, read()?)is refused, since the?could leave withtxgiven to a call that is never made. So isconsume(begin(), read()?): a resource an argument makes is the call's too. Name what may fail first. - A type parameter does not stand for a resource (
resource-inside): a function that takes any type does not know to end it.
A resource that may fail to be made is given back in a Result or an Option, the one place where another
value holds a resource: function open(path: string): Result<File, "missing">. What comes back is opened at once,
with ? (const file = open(path)?) or with match, whose arm is then the scope of the resource
(Ok(file) => read(file)). It is not named, kept, dropped or handed on as it is: _ does not take what may hold
a resource.
In the JavaScript that is written, the scope is a try whose finally ends what is still there.
#Functions
function half(n: number): Result<number, "odd"> {
if (n % 2 != 0) return Err("odd")
Ok(n / 2)
}
const double = (n: number) => n * 2
function first<T>(values: T[], fallback: T): T { values[0] ?? fallback }
The last expression of a body is what the function gives; return leaves early. A function declared with function
writes the types of its parameters and of its result (no result type: it gives nothing). A function written in place
(x => …) takes the types it is not given from where it stands. Functions declared at the top of a file may call each
other in any order.
A line ends where its expression ends. A ( or a [ at the start of a line starts a new expression: it never
continues the line above.
After =>, a { opens a body, unless it is followed by name: or by ...: then it is a record
(item => { name: item.label, price: 0 }).
#Errors are values
function quarter(n: number): Result<number, "odd" | "negative"> {
if (n < 0) return Err("negative")
Ok(half(half(n)?)?)
}
value?gives the value of anOkor of aSome, and otherwise leaves the function with theError theNone. The function must say so in its result type, or the?is refused.option ?? fallbackgives the value, or the fallback when there is none.- A
Resultor anOptionthat nobody reads is refused (must-use). panic("message")stops the program: for a bug, not for an error to hand on. Nothing in the language catches it. A call to the outside does not make anErrof it either: what stops the program in an argument of the call, or in a function the outside was handed and called, goes through the call. The same holds for what the engine throws there (a stack that ran out, a text too long). Where the outside catches it and goes on, the program stays stopped: no function handed to the outside runs again, and the call that comes back does not go on.
Where JavaScript would throw or give undefined, the type says it:
| Written | Gives |
|---|---|
values[2] | Option<T> |
record.optionalProperty | Option<T> |
a / b, a % b, a ** b on two bigints | Option<bigint> (division by zero, power below zero) |
BigInt(n) | Option<bigint> (a number that is not whole) |
text.toNumber() | Option<number> (a text that is no number, and one that says Infinity or a number too large) |
JSON.stringify(value), where the value holds a number | Result<string, JsonError> (a number that is not finite) |
n.toFixed(digits), text.repeat(count) | Option<string> |
values.find(f), values.first(), values.last(), values.indexOf(x), text.indexOf(part) | Option<…> |
JSON.parse(text) | Result<unknown, JsonError> |
Type.parse(value) | Result<Type, ParseError> |
a call to a function declared with extern | Result<T, Thrown> |
JsonError is { kind: "json", message: string }, ParseError is { kind: "parse", path: string, expected: string }
and Thrown is { kind: "thrown", name: string, message: string, detail?: unknown }: their kind tells them apart in a
union. detail is the error as it was thrown, of unknown type: a library that says more than a name and a message
(responseText, a code) is read against a type, Refused.parse(thrown.detail?).
#Numbers that are not numbers
A number is JavaScript's, so an operation may give NaN or an infinity: 0 / 0, 1 / 0, Math.sqrt(-1). JSON
has no word for them, and JavaScript writes null in their place. Here they do not come in and do not go out:
- Read from outside, a number is finite.
Type.parse, what anexterngives back, and what a TypeScript program hands to an exported function each refuseNaNand the two infinities as « not a number »:Price.parse(JSON.parse(text)?)is anErrwhen the text is{"cents": 1e999}."Infinity".toNumber()isNone. - Written as JSON, a value that holds a
numbergives aResult<string, JsonError>: anErrwhen one of its numbers is not finite, and never anullthat nobody wrote. A value with no number in it, or with written numbers only (level: 1 | 2 | 3), gives a text as before. - So what a program reads, it can write, and read back the same.
Inside a program nothing is checked yet: 0 / 0 is a number, it is not equal to itself, and an array that
holds it is not sorted by sortedBy. No type says so. Known limits has it, and what a number
may hold is still to be decided.
#match
function area(shape: Shape): number {
match shape {
{ kind: "circle", radius } => 3.14 * radius * radius,
{ kind: "rect", width, height } => width * height,
}
}
match parseInvoice(text) {
Ok(invoice) => total(invoice),
Err({ kind: "json", message }) => 0,
Err(_) => -1,
}
A match covers every value its subject may be, or it does not compile; the message names what is left. Patterns:
| Pattern | Takes |
|---|---|
"paid", 3, true | That value |
name | Anything; inside the arm, name is what the arms above did not take |
_ | Anything |
text: string | Every value of that kind: string, number, bigint, boolean, an array type, a record type |
Some(p), None, Ok(p), Err(p) | The part of an Option or of a Result |
{ kind: "circle", radius } | The records that have these properties with these values; radius names the property, radius: p matches it. A property that may be missing is named, and the name holds an Option |
There is no narrowing by a test. if (option.isSome()) proves nothing to the compiler about option on the next
line; match gives the value a new name in the arm, and that name cannot change.
#Elements
function Row(props: { item: Item, toggle: () => void }): Markup {
<li class={if (props.item.done) "done" else "todo"}>
<button onClick={props.toggle}>toggle</button>
{props.item.label}
</li>
}
export function view(items: Item[]): Markup {
<ul id="list">
{items.map(item => <Row item={item} toggle={() => {}} />)}
</ul>
}
An element is a value of type Markup: what a program shows. It is written between tags, as in JSX, and is plain
data: nothing is shown until something that shows elements (React, with @strict-script/react) is given it.
- A tag that starts with a capital is a function of the program that takes one record, or nothing, and gives a
Markup. What it is given is checked as that record: a property that is missing, one too many or one of another type is refused. What stands between its tags is its propertychildren: Markup[]. - Any other tag is an element of what shows the program, which the language does not know. It is given texts,
numbers, booleans (
disabledalone istrue), a record of them (style={{ padding: 8 }}) and functions that take nothing (onClick={more}) or the text that was typed (onChange={text => name.set(text)}). The names of tags and of attributes are not checked, except that an attribute is written once and is not named__proto__. - Between two tags: other elements, an array of them, texts and numbers;
{expression}for a value. A boolean, anOptionor a record is refused: write the text to show. - A function given to an element is kept: it names no value that can be changed and no
let. State that an event changes is in aCell. - A
<opens an element where a value is expected and a letter follows it. After a name, a number or a closing bracket on the same line it compares (a < b,a <b), and after the name of a type it opens its arguments. &and the like are not read: a text between tags is what is written. A text with a{or a<in it is written as an expression:{"a < b"}.element.toHtml()is the element as the text of a page, for a program that answers requests. Every text and every attribute is escaped, so what the program shows is never read as markup. A flag is written by its name (checked), a style from its record, and a function is left out: a text has nobody to call it. Inside<script>and<style>, where HTML reads no escape, the text is written as it is, except what would end the element. A page starts with<!doctype html>, which the program writes before it:`<!doctype html>${page.toHtml()}`.
#async
async function size(path: string): Promise<Result<number, Thrown>> {
const text = await readFile(path, "utf8")?
Ok(text.length)
}
const sizes = await Promise.all(paths.map(path => size(path)))
- An
asyncfunction saysPromise<…>as its result (nothing: it gives aPromise<void>); its body gives what the promise will give.awaitis written in anasyncfunction only. - An
asyncfunction does not give a value of unknown type, a value of the outside, a value of a type parameter or a promise (async-result): JavaScript takes a value that has athenfor a promise, and waits for it instead of giving it. Give it inside a record. One that gives nothing (Promise<void>) does not return such a value either, nor end on one. - A promise made in the language never rejects. There is no way to make one fail: what may fail gives a promise of
a
Result. A function of the outside that gives a promise is declared withPromise<T>, and its call gives aPromise<Result<T, Thrown>>: what it throws and what it rejects with both become anErr. await call()?waits, then hands the error on.- A promise that nobody waits for is refused (
must-use).detach(promise)lets aPromise<void>run on its own. Promise.all(promises)waits for all of them;sleep(milliseconds)waits.
#Loops
for (const line of invoice.lines) {
sum = sum + line.quantity
}
while (n > 0) { n = n - 1 }
for goes through an array. break and continue are there. Most loops are shorter as map, filter, reduce.
while (true) with no break is left only by return: a function may end on it.
#What comes with the language
| On | |
|---|---|
| an array | length, map, filter, find, some, every, includes, indexOf, concat, slice(from, to), join (texts), reduce(f, start), flatMap, sum() (numbers), sum(f), sortedBy(f), reversed(), first(), last() |
| a text | length, toUpperCase, toLowerCase, trim, includes, startsWith, endsWith, split, slice(from, to), indexOf, replaceAll(part, by), chars(), repeat, toNumber |
| a number | toString(), toFixed(digits), isInteger() |
a Map | Map.from([{ key, value }, …]); size, get (an Option), has, set(key, value), without(key), keys(), values(), entries(); values.groupBy(f) makes one from an array |
a Set | Set.from(values); size, has, add, without, values() |
a Cell | Cell.of(value); get(), set(value) |
a Markup | toHtml() |
a Regex | Regex.of(source, flags), Regex.from(text, flags); test(text), find(text) (the first part that matches, an Option), findAll(text), replaceAll(text, by) (by is taken as it is). The flags are i, m, s, u: a regular expression does not remember where it was, so asking it twice gives the same answer |
an Option | map, andThen, unwrapOr, okOr(error), isSome(), isNone() |
a Result | map, mapErr, andThen, unwrapOr, ok(), isOk(), isErr() |
| the platform | Math.floor, ceil, round, trunc, abs, sqrt, min, max, random; Date.now(); console.log(text), console.error(text); JSON.parse, JSON.stringify; BigInt(n), Number(bigint); Promise.all, sleep, detach; panic(text) |
reduce always takes its starting value. JSON.stringify takes texts, numbers, booleans, arrays and records of
them, and a Map whose keys are texts, which it writes as an object; JSON.stringify(value, 2) indents. Given a
value that holds values of unknown type, it gives a Result<string, JsonError>: JSON has no word for a bigint or
for a value that holds itself, and nothing says there is none in it. Given a value that holds a number, it gives
a Result too: see « Numbers that are not numbers ». Anything else of the platform is declared with extern.
#The outside
extern "node:http" {
type Server
type IncomingMessage
type ServerResponse
function createServer(handler: (request: IncomingMessage, response: ServerResponse) => void): Server
function Server.listen(port: number): Server
const IncomingMessage.url: Option<string>
function ServerResponse.end(body: string): ServerResponse
}
extern {
type URL
function URL.new(href: string): URL
function fetch(url: string): Promise<Response>
}
An extern declares what a JavaScript module has: a package, a node: module, a file. Without a module it declares
globals of the platform. A module of the older kind (CommonJS) holds what it exports under default: a name the
module does not export itself is looked for there, so extern "he" { function decode(text: string): string } is
written as for any module. Date is the one name of the platform an extern may declare as a type
(type Date, function Date.new(milliseconds: number): Date): the language has Date.now() and no date of its own.
It may declare:
| Declaration | Reached with | Becomes |
|---|---|---|
type Name | A type of the outside: its values are held and handed back, never looked into | |
type Name<T> | One that takes types: Ref<number>. What it was made with says what comes back from it. A Ref<number> is not a Ref<string> | |
function name<T>(value: T): Name<T> | name(1) | A function of the outside that takes types. In a method or a property of Name<T>, T is the one of the value: const Ref.value: T |
function name(…): T | name(…) | A call of the function |
function Name.method(…): T | value.method(…) | A call of the method on a value of that type |
function Name.new(…): Name | Name.new(…) | new Name(…) |
static function Holder.name(…): T | Holder.name(…) | A call of a function that something of the outside holds: Date.now(), AbortSignal.timeout(…), path.posix.join(…). Holder is its name out there, and is no type of the program |
static const Holder.name: T | Holder.name | A read of what it holds: Number.MAX_SAFE_INTEGER |
const name: T | name | A read of the value |
const Name.property: T | value.property | A read of the property |
A type the outside is given and gives back stands for data that crosses both ways: a text, a number, a boolean,
a record or an array of them, a value of the outside. Not an Option, a function, a value of unknown type, or a
type parameter of the program (not-data, where the call is made). A value written at the call makes the type at
large: ref({ count: 0 }) is a Ref<{ count: number }>, since others will give it other counts. What comes back is
read against that type each time, as anything that comes back is.
extern "vue" {
type Ref<T>
function ref<T>(value: T): Ref<T>
const Ref.value: T
function watch<T>(source: Ref<T>, told: (value: T) => void): () => void
}
Everything that reaches the outside gives a Result<T, Thrown>, a read included (a getter may throw):
- what is thrown becomes an
Err; - what comes back is read against the declared type as the program runs. A declaration that is wrong gives an
ErrnamedTypeMismatchwhere the call is made, not a wrong value three functions later; - declared with
Promise<T>, it gives aPromise<Result<T, Thrown>>, and a rejection is anErrtoo.
What crosses the boundary:
| Given to the outside | Texts, numbers, booleans, bigints, records, arrays and unions of them; values of the outside; a function. A record or an array is given as a copy: what the outside does to it, it does not do to a value of the program. A value of the outside is handed back as it is, the same one |
| Coming back | The same, and Option (undefined and null are read as None), a Map whose keys are texts (read from an object), or unknown to read later |
| A function coming back | Declared as what it takes and gives: function adder(by: number): (n: number) => number. Calling it reaches the outside again, so in the program it gives a Result: the call above gives a Result<(n: number) => Result<number, Thrown>, Thrown>. What it throws is an Err, what it gives is read against the type declared, and what it is given goes out as a copy. It may stand in a record or an array the outside gives, or in an Option; not in a type that names itself |
| A function given to the outside | It takes what may come back and gives what may be given. Each time the outside calls it, its arguments are read against its types; called with something else it does not run, and the caller gets an exception. A record or an array it gives back goes out as a copy |
Type.parse(value) reads a value of unknown type the same way. What it gives is a new value that holds what the type
names and nothing else: a property the type does not know is left behind.
A record is closed, so an object whose keys are not known in advance is not a record: it is a Map<string, V>.
type Answer = { choice: string, scores: Map<string, number> }
const answer = Answer.parse(JSON.parse(`{"choice":"b","scores":{"a":0.2,"b":0.7}}`)?)?
answer.scores.get(answer.choice) // Some(0.7)
JSON.stringify(answer) // Ok, with the same text again
A type that is read may hold unknown: that part is kept as it came, to be read later or written back
(Map<string, unknown> is an object of any shape).
The keys may be written values (Map<"spam" | "promo", number>): a key that is none of them is left behind, as a
property a record does not know. A dictionary comes in from the outside; it is not given to it, since a Map is not
what JavaScript takes for an object.
#Modules
import { total, Invoice } from "./invoice.sts"
An import names a .sts file by its path, and takes types and values by the same list. Two files do not import each
other, directly or through others.
For each name.sts the compiler writes name.js (an ECMAScript module), name.d.ts and name.js.map. A TypeScript
project imports the module as any other: records are plain objects, typed read-only; an Option is
{ some: true, value } | { some: false } and a Result is { ok: true, value } | { ok: false, error }.
What a TypeScript or JavaScript program imports is each function behind a door. It was told the types by the
.d.ts, and can give anything: a cast, a value typed any, what JSON.parse gave.
| What it gives | Each argument is read against its type into a value of the program's own, as Type.parse reads one. A call with something else throws a TypeError in the caller, with the place and what was expected, before the function runs. A property the type does not know is left behind |
What it gives to be changed (mut) | Read the same way; what the function did is then written into the value the caller holds. What that value now holds goes out as its type says: a record or an array in it that is not itself to be changed is the program's, frozen, and a function is behind a door. A part the record owns (mut items) is written into the value the caller holds for it. A value that is frozen or sealed, or that is given twice in the call, is refused before the function runs; one that turns out not to take what is written is said to the caller, and the program is not stopped for it |
| A function or a promise it gives | Its type says it does not fail. The program calls it, reads what it gives back against its type, and is stopped when it throws, rejects or gives something else. What the program lends it to change (mut) is another value than the program's: what the function left in it is read against its type, and written back |
| What it is given back | Data it cannot change: it is frozen, since the program may still hold it, and when it is handed back it is known again and not read a second time. A Map or a Set is another one than the program's. A regular expression is another one too. A function is behind a door of its own, wherever it is held. What was made to be changed (mut) is the caller's; what it holds that is not to be changed is frozen |
A Cell | The one the program made, known by who made it and by the type it was given out as: a cell of numbers is not handed where a cell of texts is asked for. It shows what it holds and has nothing to write it with. What it holds is given to who reads it as anything goes out: frozen when it is data, another Map or Set, a function behind a door. A framework writes a cell through the runtime library, which reads the value against the type of the cell |
| A function given to an element | Behind a door too: what shows the element calls it with nothing or with the text that was typed, and anything else is refused |
What is shown (Markup) | What the program made, frozen: an element written elsewhere is not one. A function of the program that gives an element (<Row … />) is handed to what shows it behind a door, with what it is to be called with |
| A resource | The outside is given a handle of it, with nothing in it, and holds that until it hands it back to a function that takes a resource of that kind, once: after that the handle stands for nothing. One lent to a function of the outside is lent for the time of the call; one the outside lends to a call (mut tx) is not handed back, nor lent again, until that call returns |
| After what stops the program | No exported function runs again: each throws what stopped it. One that was waiting (await) does not go on, and a panic stops the program where it is, also in a function that runs on its own (detach) |
A file of the language that imports the function calls the function itself, with no door: the compiler checked that
call. A function that takes what its caller cannot vouch for still says so: it takes unknown, which is not looked
into, and reads it with Type.parse where it chooses.
#How deep a text is nested
A text nested more than 100 deep is refused (too-deep), at the place where it goes too deep: a value in a value, a
type in a type, a body in a body, a template or an element in another. A link of some chains counts as a level:
a.b.c, f()(), T[][], a ?? b ?? c, and each else if. What is long and not nested has no limit: a body of
ten thousand statements, an array of ten thousand values, a union of ten thousand texts, and a chain of
operations (a + b + c, a && b || c), which is as long as it needs to be. A part that is given a name starts again
from where the name stands: a const for a part of an expression, a type for a part of a type, a function for a
part of a body.
#Not in the language yet
- A resource held inside another value, and one that an
asyncfunction gives back. - A collection that is shared and changed in place: a
Cellis given another value each time. - Lending to be read to a function held in a value, or one that hands its parameter to a function written in place.
- An element of an array, or a value of a
Map, changed in place: it is replaced. - A way to ask for « a value that has these properties, and maybe others ».
- Tuples, explicit type arguments at a call (
f<number>(x)), destructuring inconst. - An editor: there is a command line, with messages that say where, what, and what to write instead.