Skip to content

接口 in TypeScript

如何 定义对象 shapes 使用接口, extend 它们, and use 它们使用类.

你将学到

  • 如何 定义接口 for 对象 shape
  • 可选 and readonly 属性 in 接口
  • 如何 extend 接口到 构建 on existing shapes
  • 当到 选择接口 over 类型 aliases

概念讲解

Defining Object Shapes

An interface describes the shape of an object — which properties it has and their types. You define one with the 接口 keyword: 接口 用户 { id: 数字; name: 字符串; }. Any object assigned to a 用户-typed variable must have those properties with matching types. Interfaces are the most common way to type objects, API responses, and configuration objects.

Optional and Readonly Properties

Mark a property as optional with a question mark: email?: 字符串 — the property may be absent. Mark a property as readonly with the readonly keyword: readonly id: 数字 — it can be read but not reassigned after creation. These modifiers let you express intent: an ID should never change, and an email might not be set yet.

Extending Interfaces

Interfaces can extend one or more other interfaces, inheriting all their properties. 接口 Admin extends 用户 { permissions: 字符串[]; } has all of 用户's properties plus permissions. This composition lets you build complex types from simple ones. Interfaces are also mergeable — declaring the same interface name twice combines their properties, which is useful for extending library types.

示例代码

              // Basic interface — describes the shape of a user object.
interface User {
  readonly id: number;
  name: string;
  email?: string;       // optional
  isActive: boolean;
}

// Extending an interface — Admin has all User properties plus more.
interface Admin extends User {
  permissions: string[];
  lastLogin?: Date;
}

const user: User = { id: 1, name: "Alice", isActive: true };
const admin: Admin = {
  id: 2,
  name: "Bob",
  isActive: true,
  permissions: ["read", "write"],
};

// readonly prevents reassignment.
// user.id = 99; // ❌ Error: cannot assign to 'id' because it is readonly.
console.log(user.name, admin.permissions);
            

接口描述对象 shapes. 可选 (?) 属性可能是 missing, readonly 属性 cannot 是更改. extends inherits 所有属性从 parent 接口.

动手试一试

常见错误

错误写法

添加 excess 属性那个接口做 不定义

正确做法

TypeScript 检查 for excess 属性 on 对象 literals. 如果你 需要 extra 字段, extend 接口 or use 类型 assertion for known additional 数据.

错误写法

Forgetting 那个接口是 结构, 不 nominal

正确做法

TypeScript uses 结构输入 — 任何对象使用正确 shape matches 接口, 偶数如果它 是不 explicitly declared 到 implement 它.

练习 接口 in TypeScript

8 个练习

练习 接口 in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误