Skip to content

接口

在 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
};
编程洪同学服务平台是一个广泛收集编程相关内容和资源,旨在满足编程爱好者和专业开发人员的需求的网站。无论您是初学者还是经验丰富的开发者,都可以在这里找到有用的信息和资料,我们将助您提升编程技能和知识。
专业开发
高端定制
售后无忧
站内资源均为本站制作或收集于互联网等平台,如有侵权,请第一时间联系本站,敬请谅解!本站资源仅限于学习与参考,严禁用于各种非法活动,否则后果自行负责,本站概不承担!