TypeScript 接口

接口(Interface)用来"规定一个对象应该长什么样":有哪些属性、各自什么类型、提供哪些方法。它只存在于编译期、运行时不产生任何代码,却能让数据在传递过程中始终符合约定,是 TypeScript 组织"数据契约"的核心工具。

定义与使用

interface Person {
  name: string;
  age: number;
}
const p: Person = { name: "张三", age: 30 }; // 形状匹配,通过
console.log(p.name); // 输出:张三

多余的属性也会报错,这种按"结构形状"检查的机制称为结构化类型(鸭子类型):只要形状符合,类型就兼容。

可选属性与只读属性

interface Config {
  url: string;
  timeout?: number; // 可选:可有可无
  readonly apiKey: string; // 只读:赋值后不可修改
}
const cfg: Config = { url: "https://a.com", apiKey: "k-001" };
console.log(cfg.url); // 输出:https://a.com
console.log(cfg.timeout); // 输出:undefined(未提供)

方法与函数类型

interface Animal {
  name: string;
  speak(voice: string): void; // 方法:参数和返回类型都要声明
}
const dog: Animal = {
  name: "旺财",
  speak(v) {
    console.log(`${this.name}: ${v}`);
  },
};
dog.speak("汪汪"); // 输出:旺财: 汪汪

// 接口也可以描述函数本身
interface Calc {
  (a: number, b: number): number;
}
const add: Calc = (a, b) => a + b;
console.log(add(1, 2)); // 输出:3

继承与实现

interface Shape {
  area(): number;
}
// 接口可以继承接口
interface Circle extends Shape {
  radius: number;
}
const c: Circle = {
  radius: 2,
  area() {
    return Math.PI * this.radius ** 2;
  },
};
console.log(c.area().toFixed(2)); // 输出:12.57

// 类用 implements 承诺满足接口
class Square implements Shape {
  side: number;
  constructor(side: number) {
    this.side = side;
  }
  area() {
    return this.side * this.side;
  }
}
const sq = new Square(3);
console.log(sq.area()); // 输出:9

索引签名

当对象的键不固定时,用索引签名描述"键与值的类型规则":

interface Scores {
  [subject: string]: number; // 任意字符串键,值必须是 number
}
const scores: Scores = { 语文: 90, 数学: 85 };
console.log(scores.语文); // 输出:90
console.log(scores["数学"]); // 输出:85

小结

接口描述对象形状,支持可选、只读、方法、继承、索引签名,还能让类通过 implements 遵守约定。它是对象、函数、类之间共享类型的首选契约,先定义好接口再写实现,代码会清晰很多。

笔记加载中…