TypeScript 進階技巧

TypeScript 提供了許多進階功能,可以讓您的程式碼更加型別安全和易於維護。

泛型(Generics)

泛型讓您可以創建可重用的元件,同時保持型別安全:

function identity<T>(arg: T): T {
    return arg;
}

const result = identity<string>("hello");

條件型別(Conditional Types)

條件型別讓您可以根據條件選擇不同的型別:

type NonNullable<T> = T extends null | undefined ? never : T;

映射型別(Mapped Types)

映射型別可以基於現有型別創建新型別:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

工具型別

TypeScript 提供了許多實用的工具型別:

裝飾器(Decorators)

裝飾器提供了一種宣告式的方式來修改類別和方法:

function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function(...args: any[]) {
        console.log(`Calling ${propertyKey}`);
        return original.apply(this, args);
    };
}

最佳實踐

  1. 充分利用型別推斷
  2. 使用嚴格的型別檢查
  3. 避免使用 any
  4. 善用工具型別

掌握這些進階技巧,讓您的 TypeScript 程式碼更加優雅和強大!