Programming

TypeScript Best Practices - Viết code type-safe và maintainable

Tổng hợp các best practices khi sử dụng TypeScript trong dự án thực tế

Dũng QB5 phút đọc29 lượt xem
TypeScript Best Practices - Viết code type-safe và maintainable

TypeScript đã trở thành tiêu chuẩn cho các dự án JavaScript quy mô lớn. Bài viết này sẽ chia sẻ các best practices để viết code TypeScript clean, type-safe và dễ maintain.

Type System Best Practices

Use Type Inference

// ❌ Bad: Unnecessary type annotation
const name: string = "John";
const age: number = 30;
const items: string[] = ["apple", "banana"];

// ✅ Good: Let TypeScript infer
const name = "John"; // inferred as string
const age = 30; // inferred as number
const items = ["apple", "banana"]; // inferred as string[]

Prefer Interfaces over Type Aliases cho Objects

// ✅ Good: Interface for objects
interface User {
  id: number;
  name: string;
  email: string;
}

// Interface can be extended
interface AdminUser extends User {
  role: "admin";
  permissions: string[];
}

// Type alias for unions, intersections, etc.
type Status = "pending" | "approved" | "rejected";
type ID = string | number;

Avoid Using any

// ❌ Bad: Using any
function processData(data: any) {
  return data.someProperty; // No type checking
}

// ✅ Good: Use unknown for truly unknown types
function processData(data: unknown) {
  if (typeof data === "object" && data !== null && "someProperty" in data) {
    return (data as { someProperty: string }).someProperty;
  }
  throw new Error("Invalid data format");
}

// ✅ Better: Use generics
function processData<T extends { someProperty: string }>(data: T) {
  return data.someProperty;
}

Utility Types

Partial, Required, Readonly

interface User {
  id: number;
  name: string;
  email: string;
  age?: number;
}

// Partial: All properties optional
type PartialUser = Partial<User>;

// Required: All properties required
type RequiredUser = Required<User>;

// Readonly: All properties readonly
type ReadonlyUser = Readonly<User>;

// Practical example
function updateUser(id: number, updates: Partial<User>) {
  // Update only provided fields
  return database.update(id, updates);
}

Pick, Omit, Record

interface Product {
  id: number;
  name: string;
  price: number;
  description: string;
  category: string;
}

// Pick: Select specific properties
type ProductPreview = Pick<Product, "id" | "name" | "price">;

// Omit: Exclude specific properties
type ProductWithoutId = Omit<Product, "id">;

// Record: Create object type with specific keys
type CategoryCount = Record<string, number>;

const categoryCounts: CategoryCount = {
  electronics: 10,
  clothing: 25,
  books: 15,
};

Advanced Types

Discriminated Unions

// Define a discriminated union for API responses
type ApiResponse<T> =
  | { status: "success"; data: T }
  | { status: "error"; error: string }
  | { status: "loading" };

function handleResponse<T>(response: ApiResponse<T>) {
  switch (response.status) {
    case "success":
      console.log("Data:", response.data);
      break;
    case "error":
      console.error("Error:", response.error);
      break;
    case "loading":
      console.log("Loading...");
      break;
  }
}

Template Literal Types

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type ApiEndpoint = "/users" | "/posts" | "/comments";

// Template literal type
type ApiRoute = `${HttpMethod} ${ApiEndpoint}`;

const route: ApiRoute = "GET /users"; // Valid
// const invalid: ApiRoute = "GET /invalid"; // Error

// Dynamic property names
type PropEventSource<Type> = {
  on<Key extends string & keyof Type>(
    eventName: `${Key}Changed`,
    callback: (newValue: Type[Key]) => void
  ): void;
};

declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;

const user = makeWatchedObject({
  firstName: "John",
  lastName: "Doe",
  age: 30,
});

user.on("firstNameChanged", (newName) => {
  console.log(`New name: ${newName}`);
});

Type Guards

Custom Type Guards

interface Cat {
  type: "cat";
  meow(): void;
}

interface Dog {
  type: "dog";
  bark(): void;
}

type Animal = Cat | Dog;

// Type guard function
function isCat(animal: Animal): animal is Cat {
  return animal.type === "cat";
}

function makeSound(animal: Animal) {
  if (isCat(animal)) {
    animal.meow(); // TypeScript knows it's a Cat
  } else {
    animal.bark(); // TypeScript knows it's a Dog
  }
}

// Type guard for arrays
function isStringArray(value: unknown): value is string[] {
  return Array.isArray(value) && value.every(item => typeof item === "string");
}

Generics Best Practices

Constrained Generics

// Generic with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const person = { name: "John", age: 30, email: "john@example.com" };
const name = getProperty(person, "name"); // string
const age = getProperty(person, "age"); // number
// const invalid = getProperty(person, "invalid"); // Error

// Generic constraints with multiple types
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

logLength("hello"); // Works: string has length
logLength([1, 2, 3]); // Works: array has length
// logLength(123); // Error: number doesn't have length

Generic Utility Functions

// Type-safe object keys
function keys<T extends object>(obj: T): Array<keyof T> {
  return Object.keys(obj) as Array<keyof T>;
}

// Type-safe array filtering
function filterNullish<T>(arr: Array<T | null | undefined>): T[] {
  return arr.filter((item): item is T => item != null);
}

// Example usage
const mixedArray = [1, null, 2, undefined, 3];
const numbers = filterNullish(mixedArray); // number[]

Error Handling

Type-safe Error Handling

// Define custom error types
class ValidationError extends Error {
  constructor(public field: string, message: string) {
    super(message);
    this.name = "ValidationError";
  }
}

class NetworkError extends Error {
  constructor(public statusCode: number, message: string) {
    super(message);
    this.name = "NetworkError";
  }
}

// Result type for error handling
type Result<T, E = Error> =
  | { success: true; value: T }
  | { success: false; error: E };

// Function returning Result
async function fetchUser(id: number): Promise<Result<User, ValidationError | NetworkError>> {
  try {
    if (id < 0) {
      return {
        success: false,
        error: new ValidationError("id", "ID must be positive"),
      };
    }

    const response = await fetch(`/api/users/${id}`);
    
    if (!response.ok) {
      return {
        success: false,
        error: new NetworkError(response.status, "Failed to fetch user"),
      };
    }

    const user = await response.json();
    return { success: true, value: user };
  } catch (error) {
    return {
      success: false,
      error: new NetworkError(0, "Network error"),
    };
  }
}

// Usage
const result = await fetchUser(123);

if (result.success) {
  console.log("User:", result.value);
} else {
  if (result.error instanceof ValidationError) {
    console.log("Validation error:", result.error.field);
  } else {
    console.log("Network error:", result.error.statusCode);
  }
}

Configuration Best Practices

tsconfig.json

{
  "compilerOptions": {
    // Type Checking
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "useUnknownInCatchVariables": true,
    "alwaysStrict": true,
    
    // Additional Checks
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    
    // Module Resolution
    "moduleResolution": "node",
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"],
      "@components/*": ["components/*"],
      "@utils/*": ["utils/*"]
    },
    
    // Emit
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["ES2020", "DOM"],
    "jsx": "react-jsx",
    "sourceMap": true,
    "declaration": true,
    "declarationMap": true,
    
    // Interop Constraints
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "**/*.test.ts"]
}

Testing with TypeScript

// Jest with TypeScript
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Button } from "./Button";

describe("Button Component", () => {
  it("should call onClick handler when clicked", async () => {
    const handleClick = jest.fn();
    const user = userEvent.setup();
    
    render(<Button onClick={handleClick}>Click me</Button>);
    
    await user.click(screen.getByRole("button"));
    
    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});

// Type-safe mocks
const mockUser: User = {
  id: 1,
  name: "Test User",
  email: "test@example.com",
};

// Mock function with types
const mockFetchUser = jest.fn<Promise<User>, [number]>();
mockFetchUser.mockResolvedValue(mockUser);

Kết luận

TypeScript không chỉ là về việc thêm types vào JavaScript. Đó là về việc sử dụng type system một cách thông minh để:

  • Catch bugs at compile time
  • Improve code documentation
  • Enable better refactoring
  • Enhance developer experience

Hãy bắt đầu với strict mode và gradually adopt các best practices này trong dự án của bạn.

Cần người làm giúp?Dịch vụ phát triển ứng dụng

Dũng QB

Lập trình viên fullstack ở Sài Gòn, viết code từ 2014. Chủ yếu viết phần mềm cho người làm marketing và bán hàng trên Facebook, TikTok, Telegram.

Về mình

Bình luận

Chưa có bình luận nào. Bạn là người đầu tiên.