What shape is the data?
Describe data once and get its type and its check at the boundary.
Everything a program didn't make itself arrives as a guess: the body of a response, a saved file, a field somebody typed into. fromServer is typed unknown, which is TypeScript's way of saying so.
Predict
Two lines into program, the code calls note.title.toUpperCase(), and your editor is happy with it. What made that safe: the : Note written after const note, or something that happens when the program runs?
Check your answer
Something that happens when it runs. decodeNote(fromServer) checks the value against Note, field by field, and only then gives you a note. The annotation alone would be a promise nobody kept.
Try it
Decode
brokeninstead offromServer. Its title is42. Before you run: does the program get as far astoUpperCase? Then putfromServerback.Decoding can fail, so by lesson 4 the failure is in its type. Add a step that decodes
brokenand usesEffect.matchto turn the outcome into a line of text:`Rejected: ${error.message}`on failure. Log it.Give a note a status that is one of two words: add
status: Schema.Literals(["todo", "done"])toNote. GivefromServerthe status"todo"andbrokena real title and the status"later". Did you have to edittype Note?The server sends ids as text. Change
idtoSchema.NumberFromStringand the two ids to"1"and"2". Inside the program, what isnote.id + 1?Go the other way. Add
const encodeNote = Schema.encodeEffect(Note)and returnyield* encodeNote(note). Before you run: what isidin the result?
About steps 1 and 5
In step 1 the program stops at the decode with Expected string at ["title"]. The bad value never reaches the line that would have crashed on it.
In step 5, id is "1" again. Decoding turned the server's text into a number, and encoding turned it back, from the same definition.
What you found
Note is a Schema: a description of data, the way an Effect is a description of work. You wrote it once and got three things from it. typeof Note.Type is the type, so the two can't drift apart. decodeUnknownEffect is the check at the door, and a value that fails it is an ordinary failure that says what was wrong and where. encodeEffect writes a value back out in the shape the outside world expects.
Without it you would keep an interface, a validator and a serialiser, and trust yourself to change all three together.
That is the first part of the course. A program is a value, with its failures and its needs in its type. Many values over time are a value. Data has a description too. The rest applies exactly these ideas to a screen, starting with the plainest question you can ask of one. What decides what's on it?
Describe data once
A Schema is a description of data. One definition gives the type, the check where data comes in and a way to write it out again.