TypeScript:Interface接口
一、核心API语法
功能 | 语法示例 | 说明 |
---|---|---|
基础属性 | name: string; | 必需属性 |
可选属性 | age?: number; | 属性名后加? |
只读属性 | readonly id: string; | 初始化后不可修改 |
函数类型 | (param: T): R; | 定义函数签名 |
索引签名 | [key: string]: any; | 动态键值类型 |
方法定义 | getPrice(): number; | 类接口中的方法定义 |
继承 | interface Square extends Shape, Color {...} | 多继承支持 |
泛型接口 | interface Result<T> { data: T; } | 类型参数化 |
二、使用场景详解
1.对象结构约束
interface Product {sku: string;name: string;price: number;inStock?: boolean; // 可选属性
}
const laptop: Product = { sku: "P100", name: "MacBook", price: 1299 };
2.函数契约定义
interface Formatter {(input: string): string;
}
const toUpper: Formatter = (str) => str.toUpperCase();
3.类实现规范
interface Serializable {serialize(): string;
}class User implements Serializable {constructor(public name: string) {}serialize() { return JSON.stringify(this); }
}
4.可索引类型
interface PhoneBook {[name: string]: number; // 字符串索引
}
const contacts: PhoneBook = { Alice: 123456, Bob: 789012 };
5.接口继承
interface Animal { legs: number; }
interface Bird extends Animal {wings: number;fly(): void;
}
const eagle: Bird = { legs: 2, wings: 2, fly: () => console.log("Flying!") };
三、高级特性
1.声明合并
interface Box { weight: number; }
interface Box { color: string; } // 自动合并
const box: Box = { weight: 5, color: "blue" };
2.混合类型
interface Counter {(start: number): void;value: number;reset(): void;
}function createCounter(): Counter {let value = 0;const counter = ((start: number) => { value = start }) as Counter;counter.value = 0;counter.reset = () => { value = 0 };return counter;
}
3.泛型约束
interface Paginated<T> {data: T[];page: number;totalPages: number;
}
const usersPage: Paginated<User> = { ... };
四、最佳实践总结
1.优先选择interface而非type当定义对象/类结构时使用interface,联合类型或元组使用type
2.合理使用修饰符
readonly
保护重要数据?
提高配置对象灵活性索引签名处理动态属性
3.设计原则
graph LR
A[基础接口] --> B[扩展接口]
C[函数接口] --> D[实现类]
E[数据模型] --> F[泛型约束]
4.性能优化
深层嵌套结构使用
extends
分解避免过度使用可选属性
泛型接口减少重复定义
核心价值:
提供编译时类型安全
增强代码可读性和可维护性
实现面向接口编程范式
支持智能编辑器的自动补全