Rook
РусскийRU

decode

The types are erased, so a value from outside, the body of a request or a file, has the type that the program says it has, and nothing checks it. decode<Order>(body) checks it when the program runs: the compiler writes the type into the JS as data, and the runtime checks the value against it. The result is (Order, error), as of any function that may fail.

A string is JSON text: it is parsed, then checked; a value of type any, such as await response.json(), is only checked. A value that fits is returned as it is, with the fields that the type does not have. A missing field is an error unless it is nullable, and the error says where the value does not fit: items[1]: expected string, got 3. Types that JSON cannot hold, such as a class, Date or Map, are a compile error.

Before the board accepts task data from a request, decode can check the incoming value against the task type. The UI and background worker can then handle validated task data instead of trusting an unchecked payload.

// The types are erased: decode checks JSON from outside against a type when the program runs
interface Order {
    id number
    items string[]
    status "new" | "paid"
    note ?string // may be missing
}

const bodies = [
    `{"id": 1, "items": ["tea", "cake"], "status": "paid"}`,
    `{"id": 2, "items": ["tea", 3], "status": "new"}`,
    `{"id": 3, "items": [], "status": "sent"}`,
    `{"items": [], "status": "new"}`,
    `{"id": 5, "items": [`,
]

for body in bodies {
    const order, err = decode<Order>(body)
    if err != null {
        console.log(err.message)
        continue
    }
    console.log("order", order.id, "of", order.items.length, "items") // err is null, so order is an Order
}