The Problem with Dynamic Typing
JavaScript is a dynamically typed language, meaning types are associated with values at runtime, not variables at compile-time. While this offers flexibility, it often leads to “Runtime Errors”—bugs that only appear when a specific line of code is executed (e.g., Cannot read property 'x' of undefined).
TypeScript (TS) is a syntactical superset of JavaScript that adds static typing. It allows developers to catch type errors during development (via the compiler or IDE) long before the code reaches a user.
The Structural Type System
TypeScript uses Structural Typing (also known as “Duck Typing”). This means that two types are compatible if they have the same shape. If an object has the required properties, it is considered a valid instance of a type, regardless of its explicit declaration.
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
// This works despite not being explicitly declared as a 'Point'
const obj = { x: 10, y: 20, z: 30 };
logPoint(obj);
Core Type Constructs
Basic Types
TypeScript extends JS with types like string, number, boolean, unknown, any, and void. The any type disables type checking and should be avoided in production code.
Interfaces and Type Aliases
- Interfaces: Primarily used to define the shape of objects. They support “declaration merging” (you can define the same interface multiple times and TS will merge them).
- Type Aliases: Can represent objects, but also unions, primitives, and tuples.
Union and Intersection Types
- Unions (
|): A value can be one of several types.string | numbermeans the variable can be either. - Intersections (
&): Combines multiple types into one. The value must satisfy all types.
Generics: Reusable Logic
Generics allow you to create components (functions, classes, interfaces) that work with a variety of types while maintaining type safety. They act as “type variables.”
function wrapInArray<T>(input: T): T[] {
return [input];
}
const numArr = wrapInArray<number>(5); // T becomes number
const strArr = wrapInArray("text"); // T is inferred as string
The TypeScript Compiler (tsc)
TypeScript does not run in the browser. It must be transpiled into standard JavaScript. The tsc compiler performs two main tasks:
- Type Checking: Validates that the code adheres to the defined types.
- Downleveling: Converts modern TS/JS into older versions (like ES5) for compatibility with older browsers.
Which keyword in TypeScript creates a type that represents the 'either-or' relationship between multiple types?
Why Use TypeScript?
- Self-Documenting Code: Types reveal the developer’s intent and expectations.
- Refactoring Confidence: The compiler instantly flags all locations that break when a function signature or object shape changes.
- Improved Tooling: Enables powerful IDE features like “Go to Definition,” “Find Usages,” and intelligent autocomplete.