fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[TypeScript] 第1544天 什么是TypeScript接口?

Open haizhilin2013 opened this issue 2 years ago • 2 comments
trafficstars

第1544天 什么是TypeScript接口?

3+1官网

我也要出题

haizhilin2013 avatar Jul 07 '23 20:07 haizhilin2013

接口就是用来描述对象或者类的具体结构,约束他们的行为

BrianLiubr avatar Jul 18 '23 02:07 BrianLiubr

在 TypeScript 中,接口(interface)是一种结构化的类型声明,用于定义对象的形状。接口可以描述对象、函数、类等的类型结构,并且可以扩展和组合其他接口。接口的主要作用是提供一种契约,用于约束实现该接口的对象或类必须遵守特定的结构和类型约定。

接口的基本用法

定义对象结构

接口最常见的用法是定义对象的结构。下面是一个简单的接口示例:

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

const person: Person = {
    name: "John",
    age: 30
};

在这个示例中,Person 接口定义了一个对象的结构,要求该对象必须具有 nameage 属性,并且它们的类型分别为 stringnumber。变量 person 符合 Person 接口的要求,因此编译器不会报错。

可选属性

接口中的属性可以是可选的,使用 ? 标记:

interface Person {
    name: string;
    age?: number;
}

const person1: Person = {
    name: "John"
};

const person2: Person = {
    name: "Jane",
    age: 25
};

在这个示例中,age 属性是可选的,因此 person1 没有 age 属性也是合法的。

只读属性

接口中的属性可以是只读的,使用 readonly 标记:

interface Person {
    readonly name: string;
    age: number;
}

const person: Person = {
    name: "John",
    age: 30
};

// person.name = "Jane"; // 错误:name 是只读属性

在这个示例中,name 属性是只读的,因此尝试修改它会导致编译错误。

定义函数类型

接口可以用于定义函数类型:

interface SearchFunc {
    (source: string, subString: string): boolean;
}

const mySearch: SearchFunc = function(src: string, sub: string): boolean {
    return src.includes(sub);
};

在这个示例中,SearchFunc 接口定义了一个函数类型,该函数接受两个 string 类型的参数,并返回一个 boolean 类型的结果。

定义索引签名

接口可以包含索引签名,用于描述那些具有动态属性的对象:

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

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

在这个示例中,StringArray 接口表示索引为数字且值为字符串的数组。

扩展接口

接口可以通过 extends 关键字扩展另一个接口,从而继承其属性和方法:

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

const square: Square = {
    color: "blue",
    sideLength: 10
};

在这个示例中,Square 接口扩展了 Shape 接口,具有 colorsideLength 属性。

混合类型

接口可以描述具有多种类型的对象,例如具有属性和方法的对象:

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

const counter: Counter = function(start: number) {
    return "Counter started at " + start;
} as Counter;
counter.interval = 5;
counter.reset = function() {
    console.log("Counter reset");
};

在这个示例中,Counter 接口描述了一个既可以作为函数调用,又具有属性和方法的对象。

接口和类

接口可以用于定义类的类型结构,并通过 implements 关键字强制类实现接口:

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date;

    constructor(h: number, m: number) {
        this.currentTime = new Date();
    }

    setTime(d: Date) {
        this.currentTime = d;
    }
}

在这个示例中,Clock 类实现了 ClockInterface 接口,必须提供接口中定义的属性和方法。

总结

TypeScript 中的接口是一种灵活且强大的类型系统,用于定义对象、函数、类等的类型结构。接口可以扩展、组合和描述复杂的类型,从而提供强大的类型检查和代码提示功能,帮助开发者编写更健壮和可维护的代码。

llccing avatar Jun 26 '24 07:06 llccing