TypeScript: Adding Types
TypeScript is JavaScript with a type checker — annotate values, let inference do the rest, and catch whole classes of bugs before you run.
TypeScript (TS) is a superset of JavaScript: every valid JS file is valid TS, plus you can add type annotations. A compiler checks those types and flags mistakes before the code runs, then strips the types away to produce plain JavaScript.
let title: string = "Quest";
let count: number = 3;
let done: boolean = false;
// inference: TS already knows this is a number
let score = 10; // score: number
function double(n: number): number {
return n * 2;
}
console.log(double(score));You rarely annotate everything — TypeScript infers most types. You mostly annotate function parameters and tricky spots; the compiler propagates the rest.
#Catching bugs early
function greet(name: string) {
return "Hi, " + name.toUpperCase();
}
greet("Ada"); // ✅ fine
// greet(42); // ❌ TS error: number is not assignable to string
// (a real bug caught before the code ever runs)
console.log(greet("Ada"));Types vanish at runtime
TypeScript types exist only during development and compilation. The emitted JavaScript has no types — so TS adds zero runtime cost. (When you Run this lesson's code, the types are stripped and the plain JS executes.)
What is the main benefit of TypeScript over plain JavaScript?
Key takeaways
- TypeScript = JavaScript + a compile-time type checker.
- Annotate with `name: type` (`string`, `number`, `boolean`, arrays, etc.).
- TS infers most types — you mainly annotate function parameters.
- Type errors are caught before running; types are stripped from the emitted JS (no runtime cost).
TypeScript reports an error on the last line. Why is that a good thing?
function greet(name: string) {
return 'Hi ' + name.toUpperCase();
}
greet(42);What type does TypeScript infer for `score` here?
let score = 10;Annotate the parameter so it must be a number.
function square(n number) { return n * n; }
Annotate this function so it only accepts two numbers and returns a number:
``ts function add(a, b) { return a + b; } ``
Try it live — edit the code and hit Run to see the output: