TypeScript接口 #

一、接口基础 #

1.1 什么是接口 #

接口是TypeScript中定义对象类型的主要方式,它描述了对象的结构,包括属性和方法的类型。

typescript
interface User {
    name: string;
    age: number;
}

function greet(user: User): string {
    return `Hello, ${user.name}!`;
}

const user: User = {
    name: 'TypeScript',
    age: 12
};

greet(user);

1.2 接口的特点 #

  • 接口只描述结构,不包含实现
  • 接口会被编译器用于类型检查
  • 接口可以扩展和合并
  • 接口可以描述多种类型

二、接口属性 #

2.1 必需属性 #

typescript
interface Point {
    x: number;
    y: number;
}

const point: Point = {
    x: 10,
    y: 20
};

2.2 可选属性 #

使用?标记可选属性:

typescript
interface User {
    name: string;
    age?: number;
    email?: string;
}

const user1: User = { name: 'Alice' };
const user2: User = { name: 'Bob', age: 25 };
const user3: User = { name: 'Charlie', age: 30, email: 'charlie@example.com' };

2.3 只读属性 #

使用readonly标记只读属性:

typescript
interface Config {
    readonly apiKey: string;
    readonly endpoint: string;
}

const config: Config = {
    apiKey: 'abc123',
    endpoint: 'https://api.example.com'
};

config.apiKey = 'new-key';

2.4 动态属性名 #

typescript
interface StringMap {
    [key: string]: string;
}

const map: StringMap = {
    name: 'TypeScript',
    version: '5.4'
};

2.5 混合索引签名 #

typescript
interface Dictionary {
    [key: string]: string | number;
    length: number;
    name: string;
}

const dict: Dictionary = {
    length: 3,
    name: 'My Dictionary',
    key1: 'value1',
    key2: 'value2'
};

三、接口方法 #

3.1 方法定义 #

typescript
interface Calculator {
    add(a: number, b: number): number;
    subtract(a: number, b: number): number;
    multiply(a: number, b: number): number;
    divide(a: number, b: number): number;
}

const calc: Calculator = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => a / b
};

3.2 方法简写 #

typescript
interface Logger {
    log(message: string): void;
    error(message: string): void;
}

const logger: Logger = {
    log(message) {
        console.log(`[LOG] ${message}`);
    },
    error(message) {
        console.error(`[ERROR] ${message}`);
    }
};

3.3 可调用接口 #

typescript
interface Add {
    (a: number, b: number): number;
}

const add: Add = (a, b) => a + b;

console.log(add(1, 2));

3.4 构造签名 #

typescript
interface AnimalConstructor {
    new (name: string): Animal;
}

interface Animal {
    name: string;
    speak(): void;
}

function createAnimal(ctor: AnimalConstructor, name: string): Animal {
    return new ctor(name);
}

四、接口继承 #

4.1 单继承 #

typescript
interface Animal {
    name: string;
    age: number;
}

interface Dog extends Animal {
    breed: string;
    bark(): void;
}

const dog: Dog = {
    name: 'Max',
    age: 3,
    breed: 'Golden Retriever',
    bark() {
        console.log('Woof!');
    }
};

4.2 多继承 #

typescript
interface Printable {
    print(): void;
}

interface Serializable {
    serialize(): string;
}

interface Document extends Printable, Serializable {
    title: string;
    content: string;
}

const doc: Document = {
    title: 'My Document',
    content: 'Hello, World!',
    print() {
        console.log(`${this.title}: ${this.content}`);
    },
    serialize() {
        return JSON.stringify({ title: this.title, content: this.content });
    }
};

4.3 覆盖继承的属性 #

typescript
interface Base {
    id: string | number;
}

interface Derived extends Base {
    id: number;
}

const obj: Derived = {
    id: 123
};

五、接口合并 #

5.1 声明合并 #

同名接口会自动合并:

typescript
interface User {
    name: string;
}

interface User {
    age: number;
}

const user: User = {
    name: 'TypeScript',
    age: 12
};

5.2 非函数成员 #

非函数成员必须唯一:

typescript
interface Box {
    size: number;
}

interface Box {
    size: string;
}

5.3 函数成员 #

函数成员会被重载:

typescript
interface Document {
    createElement(tagName: string): HTMLElement;
}

interface Document {
    createElement(tagName: 'div'): HTMLDivElement;
    createElement(tagName: 'span'): HTMLSpanElement;
}

const doc: Document = document;
const div = doc.createElement('div');
const span = doc.createElement('span');

六、混合类型 #

6.1 对象与函数混合 #

typescript
interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    const counter = function (start: number) {
        return `Started at ${start}`;
    } as Counter;
    
    counter.interval = 100;
    counter.reset = function () {
        console.log('Reset');
    };
    
    return counter;
}

const c = getCounter();
c(10);
c.reset();
console.log(c.interval);

6.2 类与函数混合 #

typescript
interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
    (hour: number): ClockInterface;
}

interface ClockInterface {
    tick(): void;
}

function createClock(
    ctor: ClockConstructor,
    hour: number,
    minute?: number
): ClockInterface {
    if (minute !== undefined) {
        return new ctor(hour, minute);
    }
    return ctor(hour);
}

七、接口与类型别名 #

7.1 相似之处 #

typescript
interface User {
    name: string;
    age: number;
}

type UserType = {
    name: string;
    age: number;
};

const user1: User = { name: 'Alice', age: 25 };
const user2: UserType = { name: 'Bob', age: 30 };

7.2 接口的优势 #

声明合并 #

typescript
interface Window {
    customProperty: string;
}

window.customProperty = 'value';

extends继承 #

typescript
interface Animal {
    name: string;
}

interface Dog extends Animal {
    breed: string;
}

7.3 类型别名的优势 #

联合类型 #

typescript
type ID = string | number;
type Status = 'pending' | 'approved' | 'rejected';

原始类型别名 #

typescript
type Name = string;
type Age = number;

元组类型 #

typescript
type Point = [number, number];
type RGB = [number, number, number];

映射类型 #

typescript
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

7.4 选择建议 #

场景 推荐
对象类型 interface
联合类型 type
元组类型 type
需要扩展 interface
需要合并 interface
复杂类型组合 type

八、接口实现类 #

8.1 implements关键字 #

typescript
interface Printable {
    print(): void;
}

class Document implements Printable {
    print(): void {
        console.log('Printing document...');
    }
}

8.2 实现多个接口 #

typescript
interface Serializable {
    serialize(): string;
}

interface Cloneable {
    clone(): this;
}

class Data implements Serializable, Cloneable {
    constructor(private value: string) {}
    
    serialize(): string {
        return this.value;
    }
    
    clone(): this {
        return Object.create(this);
    }
}

8.3 接口继承类 #

typescript
class Control {
    private state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Button extends Control implements SelectableControl {
    select(): void {
        console.log('Button selected');
    }
}

九、实用接口示例 #

9.1 API响应 #

typescript
interface ApiResponse<T> {
    code: number;
    message: string;
    data: T;
    timestamp: number;
}

interface User {
    id: number;
    name: string;
    email: string;
}

async function fetchUser(id: number): Promise<ApiResponse<User>> {
    const response = await fetch(`/api/users/${id}`);
    return response.json();
}

9.2 配置对象 #

typescript
interface DatabaseConfig {
    host: string;
    port: number;
    username: string;
    password: string;
    database: string;
    ssl?: boolean;
    poolSize?: number;
}

function createConnection(config: DatabaseConfig) {
    console.log(`Connecting to ${config.host}:${config.port}`);
}

9.3 事件处理器 #

typescript
interface EventHandler {
    (event: Event): void;
}

interface EventEmitter {
    on(event: string, handler: EventHandler): void;
    off(event: string, handler: EventHandler): void;
    emit(event: string, data?: any): void;
}

9.4 插件系统 #

typescript
interface Plugin {
    name: string;
    version: string;
    install(app: Application): void;
    uninstall?(): void;
}

interface Application {
    use(plugin: Plugin): void;
    plugins: Plugin[];
}

十、总结 #

本章介绍了TypeScript接口的核心概念:

接口特性 #

  1. 属性类型:必需、可选、只读、动态属性
  2. 方法定义:方法签名、可调用接口、构造签名
  3. 继承机制:单继承、多继承、属性覆盖
  4. 声明合并:同名接口自动合并

接口vs类型别名 #

  • 接口适合定义对象类型
  • 类型别名适合联合类型、元组、复杂类型
  • 接口支持扩展和合并
  • 类型别名更灵活

最佳实践 #

  1. 优先使用接口定义对象类型
  2. 使用可选属性处理可选字段
  3. 使用只读属性保护不可变数据
  4. 合理使用接口继承复用类型定义
最后更新:2026-03-26