Z
ZHANK
实战技巧

TypeScript 最佳实践

总结 TS 编码规范、类型设计原则、any 最小化策略

TypeScript 最佳实践

总结 TypeScript 开发中的编码规范和设计原则。

学完本章你将: 掌握 TS 风格指南、类型设计原则。


类型优先原则

typescript
// ✅ 优先使用 interface 定义对象形状
interface User {
    id: number;
    name: string;
}

// ✅ 使用 type 定义联合/交叉/工具类型
type ID = string | number;
type Point = { x: number; y: number };

// ✅ 避免 any,优先 unknown
// ❌ function parse(data: any) {}
function parse(data: unknown): string {
    if (typeof data === "string") return data;
    return String(data);
}

善用类型推断

typescript
// ✅ 让 TS 推断(简洁)
const items = [1, 2, 3];           // number[]
const user = { name: "Alice" };    // { name: string }

// ❌ 不必要的显式标注
// const items: number[] = [1, 2, 3];

// ✅ 函数参数和返回值需要显式标注
function add(a: number, b: number): number {
    return a + b;
}

严格模式

json
{
    "compilerOptions": {
        "strict": true,
        "noUncheckedIndexedAccess": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true
    }
}

不可变性

typescript
// ✅ 使用 readonly
interface Config {
    readonly apiKey: string;
    readonly endpoints: readonly string[];
}

// ✅ as const 让值变字面量
const THEMES = ["light", "dark"] as const;
type Theme = (typeof THEMES)[number]; // "light" | "dark"

// ✅ 避免直接修改参数
function addItem<T>(items: readonly T[], item: T): T[] {
    return [...items, item]; // 返回新数组
}

总结速查

原则做法
类型优先interface 对象 / type 联合
少用 any用 unknown + 类型守卫
信任推断不必要处不写类型
strict 全开tsconfig strict: true
不可变readonly + as const