Introduction to TypeScript
Learn TypeScript: add static typing to JavaScript for safer code.
By EMEPublished: February 20, 2025
typescriptjavascripttypesstatic typingprogramming
A Simple Analogy
TypeScript is like a spell-checker for code. JavaScript lets you write anything (no guarantees), but TypeScript checks your spelling and grammar before running. Catch mistakes before they become bugs.
What Is TypeScript?
TypeScript is a superset of JavaScript that adds static types. It compiles to plain JavaScript and helps catch errors at compile-time rather than runtime.
Why Use TypeScript?
- Error prevention: Catch type errors before running
- Autocomplete: IDEs provide better suggestions
- Documentation: Types document what functions expect
- Refactoring: Rename safely, types guide changes
- Scalability: Maintainable large codebases
Basic Types
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
// Arrays
let numbers: number[] = [1, 2, 3];
let items: Array<string> = ["a", "b"];
// Union types
let id: string | number = "USER-123";
id = 123; // Also valid
// Any (avoid)
let anything: any = "could be anything";
Functions
// Function with types
function greet(name: string, age: number): string {
return `Hello ${name}, age ${age}`;
}
// Optional parameters
function sayHi(name: string, greeting?: string): string {
return `${greeting || "Hi"}, ${name}`;
}
// Arrow function
const double = (x: number): number => x * 2;
// Type checking
console.log(greet("Bob", 25)); // ✓
console.log(greet("Bob", "not-number")); // ✗ Error
Interfaces
// Define shape of object
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional
readonly createdAt: Date; // Read-only
}
const user: User = {
id: 1,
name: "Charlie",
email: "charlie@example.com",
createdAt: new Date()
};
// Function parameter
function getUserEmail(user: User): string {
return user.email;
}
Classes
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hi, I'm ${this.name}`;
}
}
const person = new Person("David", 28);
console.log(person.greet());
// With inheritance
class Employee extends Person {
employeeId: string;
constructor(name: string, age: number, id: string) {
super(name, age);
this.employeeId = id;
}
}
Practical Example
// API Response
interface ApiResponse<T> {
status: number;
data: T;
error?: string;
}
interface Product {
id: number;
name: string;
price: number;
}
// Fetch products
async function getProducts(): Promise<ApiResponse<Product[]>> {
const response = await fetch("/api/products");
const data: ApiResponse<Product[]> = await response.json();
return data;
}
// Usage with type safety
const products = await getProducts();
if (products.status === 200) {
products.data.forEach(p => {
console.log(`${p.name}: $${p.price}`);
});
}
Generics
// Generic function
function wrap<T>(value: T): { value: T } {
return { value };
}
console.log(wrap<string>("hello")); // { value: "hello" }
console.log(wrap<number>(42)); // { value: 42 }
// Generic interface
interface Container<T> {
items: T[];
count(): number;
}
class Stack<T> implements Container<T> {
items: T[] = [];
count(): number {
return this.items.length;
}
}
Best Practices
- Strict mode: Enable strict type checking
- Avoid any: Use specific types
- Use interfaces: Define data shapes
- Generics: Write reusable typed code
- Union types: Express multiple possibilities
Related Concepts to Explore
- Advanced type system (conditional types, mapped types)
- Decorators and metadata
- Module system and imports
- Type assertion and narrowing
- Framework integration (React, Angular, Vue)
Summary
TypeScript adds static typing to JavaScript, catching errors early and improving code maintainability. Master types, interfaces, and classes to build robust, scalable applications.