5

接口在TypeScript中是一个很重要的概念,使用得非常多,基本且重要。本文就让我们详细的来扒一扒这个接口。
在这里插入图片描述

什么是接口

当工厂制作一个商品时,肯定会先定好商品的制作规范,大小,形状,颜色等等。
TypeScript中也有这种规范。简单理解,接口就是用来描述对象或者类的具体结构,约束他们的行为。这也是TypeScript的核心原则之一:对结构进行类型检查。在实际代码设计中也很有好处,增强了系统的可拓展性和可维护性。大家可以在工作或者学习中慢慢体会。

如何定义

和其他语言类似, TypeScript中接口也是使用interface关键字来定义的:

普通定义一个接口Person,申明一个对象类型为person。遵照约定,那么person就必须有nameage属性。
// 接口描述一个对象
interface Person {
    name: string;
    age: number;
}

// person必须有name和age属性,不然会报错
const person: Person = {
    name: 'Tom',
    age: 21  //必须为number类型,不然会报错
}
接口中定义函数,表示约定函数的参数必须为Person实例,返回值为string
// 接口中定义函数
interface PersonFun {
    (person: Person): string;
}

let showPerson: PersonFun
// 具体实现
showPerson = function(person: Person) {
    return `hello!  ${person.name}.`;
}
为了灵活的使用接口,接口的属性是可以定义为可选的。定义时在属性值后面加个?号就代表这个属性是可选的。
// 定义可选属性
interface Student {
    name: string;
    age?: number;
}

// age 属性可选
const stu: Student = { name: 'Amy' }
TypeScript还支持定义只读属性,在属性前用readonly指定就行。
interface Person {
    name: string;
    readonly age: number;
}

const person: Person = {
    name: 'Tom',
    age: 21
}

person.age = 22; // 报错: Cannot assign to 'age' because it is a read-only property

这里有人可能会问这个readonlyconst的区别了。const是在定义变量的时候使用,而readonly则是定义属性的时候使用。

接口的实际使用

1,可索引类型
我们可以使用接口来描述可索引类型,索引签名只支持string和数字类型,然后通过索引来访问对象,就像这样:person['name'], stringArray[0]其实当使用number来索引时,JavaScript也是先转成string之后再去索引对象。

// 数字索引类型
interface ColorArray {
    [index: number]: string;
}

let color: ColorArray;
color = ['Red', 'Blue', 'Green'];

// 字符串索引类型
interface ColorMap {
    [index: string]: string;
}

let colorMap: ColorMap;
colorMap = {
    a: 'Red',
    b: 'Blue',
    c: 'Green'
};

console.log(colorMap.a);
console.log(colorMap['a']);

值得注意的是,在同时使用两种类型的索引的时候,数字索引的返回值必须是字符串索引返回值类型的子类型。

interface Names {
    [x: string]: string;
    // 值必须是string,否则会报错
    [i: number]: number; // Error: Numeric index type 'number' is not assignable to string index type 'string'.
}

2,混合接口
当你有这样一个需求,想要一个对象又能作为函数使用,又能作为对象使用,并且有自己的属性。这个时候就可以用混合接口来实现。

interface People{
    (): void;
    name: string;
    age: number;
    sayHi(): void;
}

// 这边需要用到类型断言 as 或者 <> 
function getPeople(): People{
    let people: People = (() => {}) as People; 
    people.name = 'James';
    people.age = 23;
    people.sayHi = () => { console.log('Hi!') }
}

let p = getPeople();
p();
p.age = 24;

混合接口一般用在第三方类库的声明文件,用混合接口声明函数和用接口声明的区别就在于,接口不能声明类的构造函数,但混合接口可以,其他都一样。

3,接口继承
接口继承使用extends关键字,可以让我们更方便灵活的复用。

interface People{
    name: string;
}

interface Student extends People{
    age: string;
}

let stu: Student = {name: '小明', age: 12 };

// 一个接口可以继承多个接口, 使用 ,分隔
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}

4, 接口实现
实现接口使用implement关键字

interface Foo {
    name: string;
    age: number;
    sayHello(): void;
}

class Bar implements Foo {
    name: string;
    age: number;
    sayHello(): void {
        console.log('Hello');
    }
}

是不是已经开始觉得TS很有趣了,继续学习吧,会更有趣的!


Kris
18 声望7 粉丝

前端程序员一枚。欢迎交流