Skip to content

接口

TypeScript 接口(interface)是一种抽象类型,它定义了某些属性和方法,但不提供具体实现。 接口可以用来定义对象的形状,并在不同的对象之间共享相同的属性和方法。

基本使用

typescript
interface Person {
    name: string;
    age: number;

    sayHello(): void;
}

function greet(person: Person) {
    console.log(`Hello, my name is ${person.name} and I am ${person.age} years old.`);
    person.sayHello();
}

const person: Person = {
    name: 'Alice',
    age: 25,
    sayHello() {
        console.log('Hi, I am Alice.');
    }
};

greet(person); // Output: Hello, my name is Alice and I am 25 years old. Hi, I am Alice.

可选属性

typescript
interface Person {
    name: string;
    age?: number; // 可选属性

    sayHello(): void;
}

const person: Person = {
    name: 'Alice'
};

greet(person); // Output: Hello, my name is Alice and I am undefined years old.

只读属性

typescript
interface Person {
    readonly name: string;
    age?: number;

    sayHello(): void;
}

const person: Person = {
    name: 'Alice'
};

person.name = 'Bob'; // Error: Cannot assign to 'name' because it is a read-only property.

函数类型接口

typescript
interface MathFunc {
    (x: number, y: number): number;
}

const add: MathFunc = (x, y) => x + y;
const sub: MathFunc = (x, y) => x - y;

console.log(add(2, 3)); // Output: 5
console.log(sub(5, 3)); // Output: 2

可索引类型接口

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

const myArray: StringArray = ['Alice', 'Bob', 'Charlie'];

console.log(myArray[0]); // Output: Alice
console.log(myArray[1]); // Output: Bob
console.log(myArray[2]); // Output: Charlie

类类型接口

typescript
interface Animal {
    name: string;

    eat(food: string): void;
}

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

const myDog: Dog = {
    name: 'Buddy',
    eat(food: string) {
        console.log(`${this.name} is eating ${food}.`);
    },
    bark() {
        console.log(`${this.name} is barking.`);
    }
};

myDog.eat('dog food'); // Output: Buddy is eating dog food.
myDog.bark(); // Output: Buddy is barking.

接口继承

typescript
interface Animal {
    name: string;

    eat(food: string): void;
}

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

interface Cat extends Animal {
    meow(): void;
}

const myDog: Dog = {
    name: 'Buddy',
    eat(food: string) {
        console.log(`${this.name} is eating ${food}.`);
    },
    bark() {
        console.log(`${this.name} is barking.`);
    }
};

const myCat: Cat = {
    name: 'Whiskers',
    eat(food: string) {
        console.log(`${this.name} is eating ${food}.`);
    },
    meow() {
        console.log(`${this.name} is meowing.`);
    }
};

myDog.eat('dog food'); // Output: Buddy is eating dog food.
myDog.bark(); // Output: Buddy is barking.

myCat.eat('cat food'); // Output: Whiskers is eating cat food.
myCat.meow(); // Output: Whiskers is meowing.