Introduction
TypeScript has become an essential tool in modern web development, powering everything from small projects to enterprise applications. In this first part of our three-part series, we'll explore the fundamentals that every TypeScript developer needs to know.
Prerequisites
- Basic understanding of JavaScript
- Node.js installed on your computer
- A code editor (VS Code recommended for its excellent TypeScript support)
Setting Up Your TypeScript Environment
First, let's set up a TypeScript project from scratch:
# Install TypeScript globally
npm install -g typescript
# Create a new project directory
mkdir ts-basics
cd ts-basics
# Initialize a new npm project
npm init -y
# Install TypeScript as a dev dependency
npm install typescript --save-dev
# Initialize TypeScript configuration
npx tsc --init
Core Concepts
1. Basic Types
TypeScript's type system is one of its most powerful features. Let's explore the fundamental types:
// Basic types
let fullName: string = "John Doe";
let age: number = 30;
let isEmployed: boolean = true;
// Arrays
let numbers: number[] = [1, 2, 3, 4, 5];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
// Tuple
let person: [string, number] = ["John", 30];
// Enum
enum Color {
Red,
Green,
Blue
}
let favoriteColor: Color = Color.Blue;
// Any and Unknown
let notSure: any = 4;
let mysterious: unknown = "hello";
2. Type Inference
TypeScript is smart enough to infer types in many cases:
// Type inference in action
let message = "Hello"; // TypeScript infers string type
let count = 42; // TypeScript infers number type
let isValid = true; // TypeScript infers boolean type
// Array inference
let numbers = [1, 2, 3]; // TypeScript infers number[]
3. Interfaces
Interfaces define contracts in your code:
interface User {
name: string;
age: number;
email: string;
isAdmin?: boolean; // Optional property
}
function createUser(user: User): void {
console.log(`Creating user: ${user.name}`);
}
// Using the interface
const newUser: User = {
name: "Alice",
age: 25,
email: "alice@example.com"
};
createUser(newUser);
4. Functions in TypeScript
Understanding how to type functions is crucial:
// Function with type annotations
function add(x: number, y: number): number {
return x + y;
}
// Arrow function with types
const multiply = (x: number, y: number): number => x * y;
// Optional and default parameters
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
5. Practical Project: Todo List
Let's create a simple todo list application to practice these concepts:
interface Todo {
id: number;
title: string;
completed: boolean;
dueDate?: Date;
}
class TodoList {
private todos: Todo[] = [];
addTodo(title: string): void {
const todo: Todo = {
id: Date.now(),
title,
completed: false
};
this.todos.push(todo);
}
toggleTodo(id: number): void {
const todo = this.todos.find(t => t.id === id);
if (todo) {
todo.completed = !todo.completed;
}
}
listTodos(): void {
this.todos.forEach(todo => {
console.log(`[${todo.completed ? 'X' : ' '}] ${todo.title}`);
});
}
}
// Usage
const myTodos = new TodoList();
myTodos.addTodo("Learn TypeScript basics");
myTodos.addTodo("Practice coding");
myTodos.toggleTodo(1);
myTodos.listTodos();
Common Gotchas and Best Practices
- Type Assertions: Use them sparingly
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
- Null Checking: Enable strict null checks in tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true
}
}
- Type vs Interface: Understanding when to use each
// Use interface for object definitions
interface Animal {
name: string;
makeSound(): void;
}
// Use type for unions, intersections, and primitives
type StringOrNumber = string | number;
type Point = { x: number; y: number };
Next Steps
- Practice type annotations with different data structures
- Explore the TypeScript Playground (typescript-play.js.org)
- Read through the official TypeScript documentation
- Start converting some of your JavaScript projects to TypeScript
Resources for Further Learning
- Official TypeScript Documentation
- TypeScript Playground
- Microsoft's TypeScript GitHub repository
Top comments (0)