模式切换
接口
在 TypeScript 中,接口(Interfaces)是一种定义对象结构的方式,它描述了一个对象应该具备哪些属性和方法。接口在 TypeScript 中扮演着非常重要的角色,特别是在定义组件的契约、确保代码的一致性和可维护性方面。
接口可以定义对象的形状,包括属性、方法的名称、参数以及返回值。一个类可以实现(implements)一个或多个接口,这意味着该类必须提供接口中定义的所有属性和方法的具体实现。
基本接口
typescript
interface Person {
firstName: string;
lastName: string;
age: number;
}
const john: Person = {
firstName: "John",
lastName: "Doe",
age: 30
};
只读接口
typescript
interface Person {
readonly firstName: string;
lastName: string;
}
const john: Person = {
firstName: "John",
lastName: "Doe"
};
// john.firstName = "Jane"; // 这行会报错,因为firstName是只读的
john.lastName = "Smith"; // 这是允许的
函数类型接口
typescript
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function (source: string, subString: string) {
let result = source.search(subString);
return result !== -1;
}
可选属性
typescript
interface Person {
firstName: string;
lastName?: string; // 可选属性
}
const person1: Person = {
firstName: "John"
};
const person2: Person = {
firstName: "Jane",
lastName: "Doe"
};
接口继承
typescript
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = {
name: "Buddy",
breed: "Labrador"
};
接口与类
typescript
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {
}
}
接口与数组
typescript
interface NumberArray {
[index: number]: number;
length: number;
}
let fibonacci: NumberArray = [0, 1, 1, 2, 3, 5, 8];
接口与字典
typescript
interface Dictionary {
[key: string]: any;
}
let dict: Dictionary = {
name: "John",
age: 30,
isStudent: false
};