Rook
РусскийRU

null, unions and narrowing

A value of type ?T may be null, and a value of type T may not. The fields of a ?T cannot be used without a check: the error comes at compile time, not in the user's browser.

After if todo != null the type narrows to Todo. The familiar ?. and ?? work with ?T too. When the board has no selected task, its selection can be ?Task; check it before reading task fields.

Where the program knows more than the compiler, todo! takes a value not to be null, as in TypeScript; it is not checked at runtime. A function whose result is never, one that throws or exits as process.exit, does not return, so the code after its call is narrowed as after throw.

interface Todo {
    title string
    done bool
}

const todos Todo[] = [{ title: "Buy guavas", done: false }]

// find returns ?Todo: there may be no such task
const todo = todos.find(t => t.title == "Buy guavas")

// console.log(todo.done) is a compile error: todo may be null
if todo != null {
    console.log(todo.done)     // here todo is already a Todo
}

// x! takes a value not to be null, as in TypeScript; nothing is checked at runtime,
// so a check or ?? is safer
const first = todos.find(t => !t.done)!
console.log(first.title, todo?.title ?? "none")

// A function whose result is never does not return: after its call, todo is a Todo
func fail(message string) never {
    throw error(message)
}
if todo == null {
    fail("no such task")
}
console.log(todo.title)

A type can be a union of several: string | number. The literal type "all" allows only that value, so type Filter "all" | "active" | "done" catches typos in strings. Unions narrow like ?T: with typeof, instanceof, a comparison with a literal and switch.

// A union type: a value of one of the types. Literal types catch typos in strings
type Filter "all" | "active" | "done"

func label(filter Filter) string {
    switch filter {
    case "active":
        return "active"
    case "done":
        return "done"
    default:
        return "everything"   // here filter can only be "all"
    }
}

// typeof and instanceof narrow a union: in each branch the type is more precise
func show(value string | number | string[]) string {
    if typeof value == "string" {
        return value.toUpperCase()
    }
    if typeof value == "number" {
        return value.toFixed(2)
    }
    return value.join(", ")    // only string[] is left
}

console.log(label("done"), show("guava"), show(3), show(["lychee", "papaya"]))
// label("dne") is a compile error: Filter has no such value

Messages, events and API responses are often one of several kinds, told apart by a field like kind: a tagged union. Comparing the tag narrows the value, so after message.kind == "photo" the fields of a photo can be read. An object literal chooses its member by the tag too, and a kind that does not exist is an error. Paths of fields narrow like variables, without an intermediate const: after message.caption != null the caption is a string, and after order.delivery.kind == "courier" order.delivery is the courier's delivery.

// A tagged union: each kind of message has the field kind with a value of its own
interface Text  { kind "text";  author string; body string }
interface Photo { kind "photo"; author string; emoji string; caption ?string }
interface Join  { kind "join";  author string }
type Message Text | Photo | Join

// A literal chooses its member by kind: { kind: "join", body: "hi" } is an error
const samples Message[] = [
    { kind: "join", author: "Ann" },
    { kind: "text", author: "Ann", body: "Who has the mangoes?" },
    { kind: "photo", author: "Bob", emoji: "🥭", caption: "Here, ripe ones" },
    { kind: "photo", author: "Bob", emoji: "🍍" },
]

comp Chat() {
    state messages Message[] = []

    func next() {
        messages = [...messages, samples[messages.length % samples.length]]
    }

    return <div>
        <button onClick={next()}>Next message</button>
        <ul>{for message in messages {
            // In each case, message is the member with that kind
            switch message.kind {
            case "text":
                <li><b>{message.author}:</b> {message.body}</li>
            case "photo":
                <li>
                    <b>{message.author}</b> sent {message.emoji}
                    {if message.caption != null { <i> “{message.caption}”</i> }}
                </li>
            default:
                <li><i>{message.author} joined the chat</i></li>
            }
        }}</ul>
    </div>
}

document.body.append(<Chat />)