接口与类
接口进阶
掌握接口继承、函数接口、索引签名
接口进阶
深入接口的高级用法:继承、函数接口、索引签名。
学完本章你将: 掌握接口继承、混合类型、声明合并。
接口继承
typescript
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
const square: Square = {
color: "blue",
sideLength: 10,
};
// 多重继承
interface Pen { write(): void; }
interface Eraser { erase(): void; }
interface Pencil extends Pen, Eraser {
brand: string;
}
混合类型接口
typescript
// 既是函数又有属性
interface Counter {
(): void; // 可调用
count: number; // 有属性
reset(): void; // 有方法
}
function createCounter(): Counter {
const counter = (() => {
counter.count++;
}) as Counter;
counter.count = 0;
counter.reset = () => { counter.count = 0; };
return counter;
}
const c = createCounter();
c(); c();
console.log(c.count); // 2
c.reset();
console.log(c.count); // 0
索引签名
typescript
// 字符串索引
interface StringDict {
[key: string]: string;
}
const dict: StringDict = {
name: "Alice",
city: "北京",
};
// 数字索引
interface NumberArray {
[index: number]: string;
}
const arr: NumberArray = ["a", "b", "c"];
console.log(arr[0]); // "a"
// 混合索引
interface MixedDict {
[key: string]: number | string;
length: number; // ✅
name: string; // ✅(与索引类型兼容)
// age: boolean; // ❌ 与索引类型不兼容
}
声明合并
typescript
// 同名 interface 自动合并
interface User {
name: string;
}
interface User {
age: number;
}
// 合并为:{ name: string; age: number }
const user: User = { name: "Alice", age: 25 };
// 全局扩展(如扩展 Window)
declare global {
interface Window {
myAppVersion: string;
}
}
window.myAppVersion = "1.0.0";