TypeScript 在前端项目中的实践


TypeScript 已成为现代前端项目的标配。本文分享在实际项目中的类型实践与踩坑经验。

一、基础类型与推断

充分利用类型推断,减少冗余注解:

// 让 TS 推断
const user = { name: '张三', age: 25 };

// 需要约束时再显式声明
interface User {
  name: string;
  age: number;
}

二、泛型的常见用法

1. 通用请求封装

async function request<T>(url: string): Promise<T> {
  const res = await fetch(url);
  return res.json();
}

const users = await request<User[]>('/api/users');

2. 组件 Props 泛型

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
}

function List<T>({ items, renderItem }: ListProps<T>) {
  return <ul>{items.map(renderItem)}</ul>;
}

三、实用工具类型

// 部分可选
type PartialUser = Partial<User>;

// 只读
type ReadonlyUser = Readonly<User>;

// 提取类型
type UserName = Pick<User, 'name'>;

// 排除类型
type UserWithoutId = Omit<User, 'id'>;

四、严格模式建议

开启 strict: true,逐步解决类型问题。strictNullChecks 能避免大量空指针隐患。

五、类型与运行时

类型只在编译期存在,运行时需配合 Zod、io-ts 等做校验。接口返回的数据建议「先校验再使用」。

合理使用 TypeScript,能在开发阶段发现大量潜在问题,提升协作效率。