0

TypeScript dành cho người mới bắt đầu

TypeScript đã trở thành một công cụ quan trọng trong phát triển web hiện đại, hỗ trợ mọi thứ từ các dự án nhỏ đến các ứng dụng doanh nghiệp. Trong bài viết này, chúng ta sẽ khám phá những kiến thức nền tảng mà mọi lập trình viên TypeScript khi mới bắt đầu học cho đến lúc thành thạo đều cần phải biết.

Điều kiện tiên quyết

  • Hiểu biết cơ bản về JavaScript
  • Đã cài đặt Node.js trên máy tính của bạn
  • Một trình soạn thảo mã (khuyến nghị dùng VS Code vì hỗ trợ TypeScript rất tốt)

Thiết lập môi trường TypeScript của bạn

Trước tiên, hãy thiết lập một dự án TypeScript từ đầu:

# 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

Khái niệm cốt lõi

1. Các kiểu dữ liệu cơ bản

Hệ thống kiểu của TypeScript là một trong những tính năng mạnh mẽ nhất của nó. Hãy cùng khám phá các kiểu dữ liệu cơ bản:

// 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. Suy luận kiểu (Type Inference)

TypeScript đủ thông minh để suy luận kiểu trong nhiều trường hợp:

// 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 (Giao diện)

Interfaces xác định các kết cấu trong mã của bạn:

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. Hàm trong TypeScript

Hiểu cách định kiểu cho hàm là rất quan trọng:

// 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. Dự án thực tiễn: Ứng dụng danh sách công việc (Todo List)

Hãy tạo một ứng dụng danh sách công việc đơn giản để thực hành các khái niệm này:

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();

Những lỗi thường gặp và các phương pháp hay nhất

1. Ép kiểu (Type Assertions)

Chỉ sử dụng khi thực sự cần thiết

let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

2. Kiểm tra giá trị null

Bật chế độ kiểm tra null nghiêm ngặt trong tsconfig.json.

{
    "compilerOptions": {
        "strictNullChecks": true
    }
}

3. Type vs Interface

Hiểu khi nào nên sử dụng mỗi loại.

// 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 };

Bước tiếp theo

  • Thực hành chú thích kiểu với các cấu trúc dữ liệu khác nhau
  • Khám phá TypeScript Playground (typescript-play.js.org)
  • Đọc tài liệu chính thức của TypeScript
  • Bắt đầu chuyển đổi một số dự án JavaScript của bạn sang TypeScript

Tài nguyên học tập thêm

  • Tài liệu chính thức của TypeScript
  • TypeScript Playground
  • Kho lưu trữ TypeScript trên GitHub của Microsoft

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí