In this video, you saw the two separate moments in a TypeScript program’s life, using a small piece of Spoke & Sprocket’s repair-ticket code.
Key Points
- Before the program runs, TypeScript’s checker reads your code and its types. It reports where a value doesn’t fit, and it runs nothing. When everything fits, it reports nothing.
- A type annotation, such as
: numberafter a parameter, says which kind of value belongs in that spot. You’ll write your own in a later lesson. - To run the program, Node erases the types first. What’s left is plain JavaScript, and that’s what Node runs. Your file keeps its types. Node drops them only as it loads the file.
- Types aren’t checked while your program runs. A value that arrives at run time, such as text read from a saved file with
JSON.parse(), isn’t checked against an annotation. Data from outside has to be checked by code that runs, which a later lesson shows.
The Code
The shop’s ticket function, with its annotations:
tickets.ts
function nextTicket(last: number): number {
return last + 1;
}
console.log(nextTicket(41));
The checker reports nothing for this file. Once the types are erased, the JavaScript that’s left prints the next ticket number:
42
The same file, tickets.ts, with its last line replaced by two lines that read the last ticket number from the shop’s saved file, where it’s stored as text:
tickets.ts
function nextTicket(last: number): number {
return last + 1;
}
const saved = JSON.parse('{"lastTicket": "41"}');
console.log(nextTicket(saved.lastTicket));
The checker reports nothing here either. JSON.parse() can give back any shape, so the checker doesn’t know what’s in saved and doesn’t check saved.lastTicket against number.
At run time, saved.lastTicket is the string "41", and a string plus a number joins the two:
411
Next, in Checking and Running a Project, you’ll set up both jobs on your own machine, and the checker makes its first real find in the shop’s code.