Appearance
Types
Weft is statically typed. Function parameters and props carry annotations; almost everything else is inferred. The type syntax is TypeScript's, and there is no any.
The types
| type | values |
|---|---|
number, string, boolean | as in JavaScript, without coercion between them |
null | the only absence |
"open", 3, true | literal types: exactly that value |
A | B | either; T? is short for T | null |
T[] | lists |
[A, B] | tuples: fixed length, a type per position |
{ a: A, b?: B } | records; b? may be left out of a literal and is then null |
Map<K, V>, Set<T> | keyed collections, in insertion order |
(x: A) => R | functions |
Range | 0..10, 1..=10: a range of numbers |
Task<T> | the result of an async function |
json | dynamic data: what std/json's parse gives and HTTP bodies hold |
R ! E | a function's result that may be an error of type E instead (Errors) |
Error | { name: string, message: string, data: json }, a general error type |
Absence
A type without ? never holds null. A T? must be checked before use, and the check narrows it:
weft
type Todo = { title: string, note?: string }
export fn noteOf(t: Todo): string {
return t.note ?? "(no note)"
}
export fn noteLength(t: Todo): number {
if t.note == null { return 0 }
return t.note.length
}
export fn firstNote(todos: Todo[]): string? {
return todos.first()?.note
}?. and ?? work as in JavaScript. x! asserts that x isn't null; if it is, that's a bug, and the program panics with a TypeError (Errors).
Aliases and unions
type names a type. A union of string literals is the simplest enum:
weft
type Filter = "all" | "open" | "done"
type Todo = { id: number, title: string, done: boolean }
export fn visible(todos: Todo[], filter: Filter): Todo[] {
return todos.filter(t => filter == "all" || t.done == (filter == "done"))
}A union of records needs a field that tells its members apart, a tag such as kind. Testing the tag narrows the value:
weft
type Result = { kind: "ok", value: number } | { kind: "err", message: string }
export fn show(r: Result): string {
if r.kind == "ok" { return `= ${r.value}` }
return `error: ${r.message}`
}Variants
Variants are the short way to write such a union. Each member has a name and, optionally, fields:
weft
type Shape = Circle { r: number } | Rect { w: number, h: number } | Empty
export fn unit(): Shape {
return Circle { r: 1 }
}
export fn describe(s: Shape): string {
return match s {
Circle { r } => `a circle of radius ${r}`,
Rect { w, h } => `a ${w} by ${h} rectangle`,
Empty => "nothing",
}
}Shape is the union { kind: "Circle", r: number } | { kind: "Rect", w: number, h: number } | { kind: "Empty" }: the same values, in json and on the wire. A variant is made by its name (Circle { r: 1 }, Empty) and matched by its name. Variant names are in scope wherever their type is. When two types in scope have a variant of one name, write Shape.Circle.
Named construction
A record type's name makes its values the same way. Every field must be given, except optional ones, and no other:
weft
type Todo = { id: number, title: string, done: boolean }
export fn fresh(id: number, title: string): Todo {
return Todo { id, title, done: false }
}A plain record literal works too ({ id, title, done: false }). The name says what you meant, so a missing or extra field is reported at the field, against Todo.
An alias may refer to itself when the recursion goes through a list, a map or a ?:
weft
type Tree = { label: string, children: Tree[] }
export fn size(t: Tree): number {
return 1 + t.children.map(c => size(c)).sum()
}Inference
The type of a let or a derived value comes from its initializer, and a literal keeps its own type: let f = "all" is the type "all". An unannotated let mut will change, so its type comes from what the code around it does with it. Assigning only literals gives their union, so this compiles: filter is "all", which is a Filter:
weft
type Filter = "all" | "open" | "done"
fn label(f: Filter): string {
return `showing ${f}`
}
export fn current(): string {
let mut filter = "all"
return label(filter)
}
export fn next(): string {
let mut filter = "all"
filter = "open"
return label(filter)
}A bind: of it, or & of it for a mut parameter, gives it that exact type. Assigning anything else widens it to the base type, and the error that causes is reported at the assignment:
rejected by the compiler (E2001)
weft
type Filter = "all" | "open" | "done"
fn label(f: Filter): string {
return `showing ${f}`
}
export fn current(s: string): string {
let mut filter = "all"
filter = s
return label(filter)
}Its fix-it annotates the let mut, let mut filter: Filter = "all", which states the type; then the assignment must give a Filter (check s first, with is or match).
An empty list gets its item type the same way, from a push, a bind:, or what it is returned or passed as:
weft
type Todo = { title: string, done: boolean }
export fn fresh(): Todo[] {
let mut todos = []
return todos
}
export fn titles(): number {
let mut names = []
names.push("a")
return names.length
}With nothing to go by, let mut xs = [] is an error that asks for the item type: let mut xs: string[] = [].
Records are structural
Two record types with the same fields are the same type. A record with more fields converts to a type with fewer, and the extra fields are dropped (projected), not hidden:
weft
type Todo = { id: number, title: string, done: boolean }
type Summary = { id: number, title: string }
export fn summary(t: Todo): Summary {
return t
}summary returns a record with id and title only. Projection happens where a value is stored, returned or passed, and only at the top level. A list of Todo doesn't convert to a list of Summary; map it: todos.map(t => ({ id: t.id, title: t.title })).
A spread copies a record's fields into a new one, and later fields win, as in JavaScript. It is the usual way to change one field without a let mut:
weft
type Todo = { id: number, title: string, done: boolean }
export fn finish(t: Todo): Todo {
return { ...t, done: true }
}The new done keeps the type the spread gave it (boolean), so the result is still a Todo; a value of another type is an error.
Maps and sets
Map and Set are values like the others. Construct them without new. Keys are primitive: numbers, strings, booleans or null.
weft
export fn wordCounts(text: string): Map<string, number> {
let mut counts = Map<string, number>()
for w of text.split(" ") {
if w == "" { continue }
counts.set(w, (counts.get(w) ?? 0) + 1)
}
return counts
}
export fn unique(xs: string[]): string[] {
return Set(xs).values()
}Generics
A function can take type parameters. They are inferred from the arguments, or written: firstOr<string>(xs, "").
weft
export fn firstOr<T>(xs: T[], fallback: T): T {
if xs.isEmpty() { return fallback }
return xs[0]
}
export fn pair<A, B>(a: A, b: B): [A, B] {
return [a, b]
}Without a bound, inside a generic function you can pass, store and compare values of a type parameter, and nothing more, so the compiler never needs to know what T is. Two bounds lift that: T: data (only data types: it can be serialized, converted to json, tested with is against a data type, and listed with fields<T>()) and T: key (only primitives: everything data allows, plus map keys and showing in text).
weft
import { stringify } from "std/json"
export fn encode<T: data>(value: T): string {
return stringify(value)
}
export fn countBy<K: key>(items: K[]): Map<K, number> {
let mut counts = Map<K, number>()
for k of items { counts.set(k, (counts.get(k) ?? 0) + 1) }
return counts
}rejected by the compiler (E2018)
weft
import { stringify } from "std/json"
fn encode<T: data>(value: T): string { return stringify(value) }
let s = encode(() => 1)A function isn't data, so the call is rejected. There are no other bounds.
json
json holds dynamic data: null, booleans, numbers, strings, lists and string-keyed records of json. Reading a key gives json again (null when it is absent). To use the data as a typed value, test it with is, or cast it with as, which checks every field when it runs. Both parsing and casting can fail, so each goes through try (Errors):
weft
import { parse } from "std/json"
type User = { name: string, admin: boolean }
export fn parseUser(text: string): User {
let j = try parse(text)
return try j as User
}
export fn nameOf(j: json): string {
let n = j.name
if n is string { return n }
return "unknown"
}as User fails with a CastError if a required field is missing or has the wrong type, naming the field (value.admin) and the type it expected; it drops fields User doesn't have. parseUser's type is User ! SyntaxError | CastError. The other way needs no cast: every data type converts to json implicitly, so stringify(user) takes a User as it is.
A json object whose keys aren't known in advance (a translation file, a webhook's payload, an API's { [id]: item }) is read with keys(), values() and entries(), a for over its [key, value] pairs, or a cast to a Map:
weft
import { parse } from "std/json"
export fn languages(text: string): string[] {
let j = try parse(text)
let mut out: string[] = []
for [code, name] of j.entries() {
out.push(`${code}: ${name}`)
}
return out
}
export fn prices(text: string): Map<string, number> {
let j = try parse(text)
return try j as Map<string, number>
}Validating types
A validating type adds a condition to a type. it is the value; the condition is pure.
weft
type Email = string where it.includes("@") && it.length <= 254
type Age = number where it.isInteger() && 0 <= it && it < 150
type Signup = { email: Email, age: Age, name: string where it.trim() != "" }
let admin: Email = "admin@example.com"
export fn signup(j: json): Signup {
return try j as Signup
}
export fn isEmail(s: string): boolean {
return s is Email
}An Email is a string wherever a string is wanted, but a string becomes an Email only through a check: as (which fails with a CastError naming the field that failed and the type it expected), is (which narrows), or a literal the compiler checks when it compiles (admin above). Checks go all the way down: j as Signup checks each field's own condition too. Server functions check their arguments the same way when a call arrives.
rejected by the compiler (E2017)
weft
type Email = string where it.includes("@")
let bad: Email = "not an address"Attributes
Attributes are data the compiler keeps on a record type's fields (or on a type declaration): @name or @name(args), where each argument is a constant or a name. A module declares the attributes it reads; on their own they change nothing. fields<T>() lists a record type's fields with them at run time, which is how a form builder or a database schema reads them.
weft
import { fields } from "std/reflect"
attribute label(text: string)
attribute default<T>(value: T)
type Settings = {
@label("Display name") name: string,
@label("Volume") @default(5) volume: number,
}
export fn labels(): string[] {
return fields<Settings>().map(f => f.name)
}An attribute's type parameter is the type of the field it is on, so @default("loud") on volume is an error. An unknown attribute, or arguments of the wrong type, are errors too.
Bytes
Bytes is an immutable sequence of bytes, for files, images and HTTP bodies. It is data: in json it is its base64 text.
weft
export fn packet(): Bytes {
let header = Bytes.of([0x57, 0x46])
return header.concat(Bytes.fromUtf8("hello"))
}
export fn describe(b: Bytes): string {
return `${b.length} bytes, first ${b[0]}, ${b[..2].toHex()}, ${b.toBase64()}`
}
export fn key(text: string): Bytes {
return try Bytes.fromHex(text)
}Bytes.fromUtf8, Bytes.fromHex and Bytes.fromBase64 make bytes from text, and toUtf8, toHex and toBase64 read them back. Hex and base64 text can be malformed, so those two fail with std/math's ParseError.
What Weft leaves out
No any or unknown (use json), no undefined, no classes or interfaces (use records and functions), no enums (use variants or unions of literals), and no implicit conversions.