TypeScript 接口 — 定义对象形状
用 interface 定义对象结构,约束属性和方法 · 难度:进阶 · +20XP
interface — 对象的"合同"
interface(接口)用来定义对象的结构——这个对象必须有哪些属性、什么类型。就像一份"合同",不遵守就报错。
回顾:JS 中的对象可以随便加属性。TS 的 interface 让你明确定义对象长什么样。
基本用法
// 定义用户对象的结构
interface User {
name: string;
age: number;
email?: string; // ? 表示可选属性
readonly id: number; // readonly 表示只读,不能修改
}
const user: User = {
name: "张三",
age: 25,
id: 1
// email 可省略
};
// user.id = 2; // ❌ 错误!id 是只读的
接口的继承
interface Admin extends User {
role: "admin" | "superadmin";
permissions: string[];
}
const admin: Admin = {
name: "管理员",
age: 30,
id: 0,
role: "admin",
permissions: ["users.read", "users.write"]
};
实际应用
在项目中,API 返回的数据用 interface 定义:
interface ApiResponse<T> {
code: number;
data: T;
message: string;
}
// 现在你可以安全地使用 res.data
const res: ApiResponse<User> = await fetch("/api/user/1");