Introduction to TypeScript
Typed JavaScript — catch errors before they reach runtime
Skills taught: ts.type-annotations, ts.compilation, ts.type-errors, ts.inference
Type annotations and inference
// TypeScript adds type annotations to JavaScript
let username: string = 'Alice';
let age: number = 30;
let isActive: boolean = true;
// TypeScript INFERS types — you often don't need to annotate
let score = 42; // inferred as number
let greeting = 'Hello'; // inferred as string
// Type error (caught BEFORE running)
// score = 'high'; // Error: Type 'string' is not assignable to type 'number'
// Functions with typed parameters and return type
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 10)); // 15
// add('5', 10); // Error! '5' is a string
// TypeScript catches the bug immediately:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet('World'));
TypeScript vs JavaScript
// JavaScript (no types — error only at runtime)
// function multiply(a, b) { return a * b; }
// multiply('5', 10); // NaN — runtime bug, no warning!
// TypeScript (types — error at compile time)
function multiply(a: number, b: number): number {
return a * b;
}
// multiply('5', 10); // Error: Argument of type 'string' is not assignable
// The compiled JavaScript looks like plain JS:
// function multiply(a, b) { return a * b; }
// Types are ERASED at compile time — zero runtime overhead
// TypeScript knows what methods are available
const fruits: string[] = ['apple', 'banana', 'cherry'];
console.log(fruits.length); // OK
console.log(fruits.toUpperCase()); // Error: Property 'toUpperCase' does not exist on type 'string[]'
// IDE catches this instantly — no need to run the code
Tip: TypeScript types are ERASED when compiled to JavaScript. They add zero runtime overhead — the output JS is exactly what your browser runs.
Frequently Asked Questions
Do I need to annotate every variable in TypeScript?
No! TypeScript infers types from initial values. let count = 0 is automatically typed as number. You only need annotations when inference can't determine the type (function parameters are a common case), or when you want to be explicit for documentation purposes.
What is tsconfig.json?
tsconfig.json configures the TypeScript compiler. Key options: target (which JS version to emit: ES5, ES2020), strict (enable all strict checks — always use this), outDir (where to put compiled JS), include/exclude (which files to compile). Run tsc --init to generate a starter tsconfig.