Skip to content

接口

一句话解释

接口是 TypeScript construct 那个定义 shape 的对象 — 哪个属性它 有 and 它们的类型 — 不使用包含任何 implementation code.

用大白话说

interface 是一种contract for objects。 It describes what properties an object should have and what types those properties should be. Interfaces are compile-time only — they are erased when TypeScript compiles to JavaScript.

Interfaces are commonly used to type function parameters, API responses, and class shapes. They support optional properties (with ?), readonly properties, and extension (with extends).

A unique feature of interfaces is declaration merging: if you declare two interfaces with the same name, TypeScript combines them into one. This is useful for extending existing types, including built-in ones like Window.

示例

typescript
interface User {
  id: number;
  name: string;
  email?: string; // optional
}

const user: User = { id: 1, name: "Alice" };

用户接口定义 shape 的用户对象. email 属性是 可选.

常见混淆

  • 容易混淆的对象: 类型 alias

    关键区别: 接口 support declaration 合并 and 'extends'; 类型 aliases support unions, intersections, and tuples. For 对象 shapes, 要么工作.

相关术语

解读错误信息

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

查看错误

← 返回术语表