TypeScript vs JavaScript
You write task.titel instead of task.title. JavaScript says nothing: the page loads, and much later a user sees undefined where a task name should be. TypeScript would have underlined that typo the moment you typed it. That early warning is the whole idea.
The rule
TypeScript is JavaScript plus types, checked first and then erased.
Three parts, three ideas:
- JavaScript plus types. Every valid JavaScript program is also valid TypeScript syntax. TypeScript adds annotations that say what kind of value something holds.
- Checked first. Before the code runs, the TypeScript compiler reads those annotations and reports mistakes: a missing property, a number passed where a string belongs, a function called with too few arguments.
- Then erased. The compiler removes the annotations and writes plain JavaScript. Browsers and Node.js run that output; they never see a type.
Here is the task we will model all course long:
type Task = { id: number; title: string; done: boolean };
function formatTask(task: Task): string {
return `${task.id}. ${task.title}`;
}
formatTask({ id: 1, title: "Buy milk", done: false }); // fine
formatTask("Buy milk"); // error: a string is not a TaskAfter compiling, what runs is simply:
function formatTask(task) {
return `${task.id}. ${task.title}`;
}The type Task line and every : Task have vanished. So types cost nothing at runtime, and they also protect nothing at runtime: if bad data arrives from a server while the program runs, TypeScript is no longer there to stop it.
The shortcut
When you meet a TypeScript feature, ask "Does this survive into the JavaScript?" Annotations, type, and interface do not survive. Ordinary code such as functions, objects and classes does. That one question tells you whether something can affect how the program behaves or only how it is checked.
Write it
let count: number = "three";— an annotation sayscountholds a number, but the value is a string.
A common mistake is expecting a type annotation to convert or validate a value at runtime. It never does. Annotations are instructions for the checker, not for the program.
Drills
Answer fast — trust the rule.
What does a browser actually run when you build a TypeScript project?
When is the typo in task.titel reported by TypeScript?
Which of these is true about any valid JavaScript file?
A server returns { "id": "seven" } at runtime, and your code types it as Task. What does TypeScript do?
Remember
- TypeScript is JavaScript plus types, checked first and then erased.
- Ask "does this survive into the JavaScript?" to tell checking features from running code.
- Trap: annotations never convert or validate data while the program runs.
