全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-21 7 分钟 ✍️ juanwangdev

TypeScript 接口与实现

接口是 TypeScript 类型系统的核心,用于描述对象的结构契约,下面梳理核心用法。

接口基础

定义接口

TypeScript
interface User {
  name: string;
  age: number;
  email: string;
}

使用接口约束对象

TypeScript
const user: User = {
  name: "Alice",
  age: 25,
  email: "alice@example.com"
};

注意:接口仅用于类型检查,编译后不产生任何 JavaScript 代码。

接口描述函数类型

TypeScript
interface MathFn {
  (a: number, b: number): number;
}

const add: MathFn = (a, b) => a + b;
const multiply: MathFn = (a, b) => a * b;

接口描述索引类型

TypeScript
interface StringArray {
  [index: number]: string;
}

const arr: StringArray = ["a", "b", "c"];

可选属性

使用 ? 标记非必填属性:

TypeScript
interface Config {
  host: string;
  port?: number;     // 可选
  timeout?: number;  // 可选
}

const c1: Config = { host: "localhost" };
const c2: Config = { host: "localhost", port: 8080 };

只读属性

TypeScript
interface Point {
  readonly x: number;
  readonly y: number;
}

const p: Point = { x: 1, y: 2 };
// p.x = 10;  // 错误:无法分配到只读属性

接口实现

使用 implements 让类遵循接口约束:

TypeScript
interface ILogger {
  log(msg: string): void;
  error(msg: string): void;
}

class ConsoleLogger implements ILogger {
  log(msg: string): void {
    console.log(msg);
  }

  error(msg: string): void {
    console.error(msg);
  }
}

类实现多个接口

TypeScript
interface IPrintable {
  print(): void;
}

interface IStorable {
  save(): void;
}

class Document implements IPrintable, IStorable {
  print(): void {
    console.log("Printing...");
  }

  save(): void {
    console.log("Saving...");
  }
}

接口继承

TypeScript
interface Shape {
  color: string;
}

interface Circle extends Shape {
  radius: number;
}

const c: Circle = {
  color: "red",
  radius: 10
};

多继承:

TypeScript
interface A { a: string; }
interface B { b: number; }
interface C extends A, B { c: boolean; }

const obj: C = { a: "x", b: 1, c: true };

接口与类型别名的区别

特性interfacetype
对象形状描述
声明合并
继承/实现✅ extends/implements
联合类型type A = B | C
元组类型type T = [string, number]

建议:描述对象形状用 interface,需要联合/元组/复杂类型用 type

要点总结

  • 接口用 interface 定义,描述对象/函数/索引的形状
  • ? 标记可选属性,readonly 标记只读属性
  • implements 让类承诺遵循接口契约
  • 接口可继承(extends),类可实现多个接口
  • 接口仅用于类型检查,编译后消失

📝 发现内容有误?点击此处直接编辑

← 上一篇 TypeScript 联合类型与交叉类型
下一篇 → TypeScript 类与面向对象
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库