TypeScript 核心知识点(覆盖 90% 开发场景)

5 阅读4分钟

TypeScript 核心知识点(覆盖 90% 开发场景)

一、基础语法(20%)—— 搞定类型标注的核心规则

1. 基础类型(必懂)

// 原始类型(TS 自动推断,也可手动标注)
const str: string = "hello";
const num: number = 100;
const bool: boolean = true;
const n: null = null;
const u: undefined = undefined;

// 数组(两种等价写法,推荐前者)
const arr1: string[] = ["a", "b"];
const arr2: Array<number> = [1, 2];

// 元组(固定长度+类型的数组)
const tuple: [string, number] = ["name", 18];

// 任意类型(尽量少用,兜底用 unknown 替代)
let anyVal: any = "任意值";
anyVal = 100; // 无类型校验

// 未知类型(安全的 any,需类型收窄才能用)
let unkVal: unknown = "未知值";
if (typeof unkVal === "string") {
  console.log(unkVal.length); // 类型收窄后可用
}

2. 接口 / 类型别名(核心,80% 场景用 interface)

// 接口(支持扩展、合并,推荐用于对象类型)
interface User {
  id: number;
  name: string;
  age?: number; // 可选属性
  readonly phone: string; // 只读属性
}

// 类型别名(支持联合/交叉类型,更灵活)
type Status = "success" | "error" | "loading"; // 联合类型
type UserWithStatus = User & { status: Status }; // 交叉类型

// 接口扩展
interface AdminUser extends User {
  role: string;
}

3. 函数类型(必懂)

// 函数参数+返回值标注
const add = (a: number, b: number): number => {
  return a + b;
};

// 可选参数(必须放最后)
const getUser = (id: number, name?: string): User => {
  return { id, name: name || "默认名", phone: "123456" };
};

// 函数类型别名(复用函数签名)
type Fn = (x: number) => number;
const double: Fn = (x) => x * 2;

二、核心场景(60%)—— 开发中高频用到的 TS 能力

1. 泛型(核心中的核心,解决类型复用)

// 泛型函数(适配任意类型,保留类型安全)
function wrap<T>(value: T): { data: T } {
  return { data: value };
}
const res1 = wrap<string>("hello"); // { data: string }
const res2 = wrap<number>(100); // { data: number }

// 泛型接口(适配不同结构的返回数据)
interface ApiRes<T> {
  code: number;
  data: T;
}
// 复用:用户列表接口
type UserListRes = ApiRes<User[]>;
// 复用:商品接口
type GoodsRes = ApiRes<{ id: number; price: number }>;

// 泛型约束(限制泛型范围)
function getLength<T extends { length: number }>(obj: T): number {
  return obj.length;
}
getLength("abc"); // 合法
getLength([1,2]); // 合法
// getLength(100); // 报错:数字没有length

2. 类型收窄(处理 unknown / 联合类型)

// 类型守卫(typeof)
function print(val: string | number) {
  if (typeof val === "string") {
    console.log(val.toUpperCase()); // 收窄为string
  } else {
    console.log(val.toFixed(2)); // 收窄为number
  }
}

// 类型守卫(instanceof)
class Animal {}
class Dog extends Animal {
  bark() {}
}
function fn(animal: Animal) {
  if (animal instanceof Dog) {
    animal.bark(); // 收窄为Dog
  }
}

// 类型守卫(in)
interface Cat {
  meow: () => void;
}
function pet(animal: Dog | Cat) {
  if ("bark" in animal) {
    animal.bark();
  } else {
    animal.meow();
  }
}

3. 工具类型(TS 内置,直接用)

不用记底层实现,记住「什么时候用」即可:

// Partial:把所有属性变成可选
type PartialUser = Partial<User>; // { id?: number; name?: string; ... }

// Required:把所有属性变成必选
type RequiredUser = Required<User>; // 去掉age的?

// Pick:挑选指定属性
type UserBase = Pick<User, "id" | "name">; // 只保留id和name

// Omit:排除指定属性
type UserWithoutPhone = Omit<User, "phone">; // 排除phone

// Record:快速定义键值对类型
type Dict = Record<string, number>; // { [key: string]: number }

4. 异步 / Promise 类型(前端请求必用)

// Promise 类型标注
const fetchData = async (): Promise<User> => {
  const res = await fetch("/api/user");
  return res.json();
};

// 调用异步函数
const useData = async () => {
  const user = await fetchData(); // user 是 User 类型
  console.log(user.name);
};

三、React 结合场景(10%)—— 前端开发专属

1. 组件 Props 类型

// 无 React.FC 写法(推荐)
interface ButtonProps {
  text: string;
  onClick?: () => void;
  children?: React.ReactNode;
}
const Button = ({ text, onClick }: ButtonProps) => {
  return <button onClick={onClick}>{text}</button>;
};

2. Hooks 类型标注

// useState(复杂类型手动标注)
const [user, setUser] = useState<User | null>(null);

// useRef(DOM/普通值区分)
const inputRef = useRef<HTMLInputElement>(null);
const timerRef = useRef<NodeJS.Timeout | null>(null);

// 事件类型(React 内置)
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
  console.log(e.currentTarget);
};

四、避坑 & 实战技巧(核心原则)

1. 少用 any,多用 unknown / 类型收窄

any 会关闭 TS 校验,是「类型安全的敌人」,兜底优先用 unknown。

2. 类型定义和数据结构「完全匹配」

// 错误:数组类型和数据不匹配
interface Res {
  items: string[]; // 实际是对象数组
}
// 正确:
interface Res {
  items: { id: number; name: string }[];
}

3. 异步函数必标注 Promise 或让 TS 自动推断

// 推荐:自动推断(简洁)
const test = async () => {
  const res = await instance.get<ApiRes<User>>("/data");
  return res.data;
};
// 推荐:手动标注(清晰)
const test = async (): Promise<ApiRes<User>> => {
  const res = await instance.get<ApiRes<User>>("/data");
  return res.data;
};

总结(90% 场景核心要点)

  1. 基础层:掌握基础类型、接口 / 类型别名、函数类型标注,搞定 80% 的基础类型场景;
  2. 核心层:泛型(复用类型)、类型收窄(处理未知类型)、内置工具类型,搞定复杂场景;
  3. 实战层:Promise 异步类型、React 组件 / Hooks 类型,适配前端业务开发;
  4. 原则层:少用 any、类型和数据匹配、异步函数标注 Promise,保证类型安全。

这套知识点覆盖了前端开发中 90% 的 TS 场景,不用死记硬背,在项目中落地 2-3 个组件 / 接口请求,就能熟练掌握。遇到小众场景(如装饰器、高级类型),按需查文档即可。