首页 > 技术文章 > TypeScript接口

lone5wolf 2022-01-22 20:37 原文

TypeScript接口

接口是一种规范的定义,它定义了行为和动作的规范;在程序设计里面,接口起到一种限制和规范的作用。接口定义了某一批类所需要遵守的规范,接口不关心这些类的内部状态数据,也不关心这些类里方法的实现细节,它只规定这批类里必须提供某些方法,提供这些方法的类就可以满足实际需要。

一、接口类别:

   1、属性接口对传入对象的约束

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

function printPeople(person:IPeople) {
    console.log("姓名:"+person.name);
    console.log("年龄:"+person.age);
}

printPeople({name:'张三',age:25}); //正确
printPeople("123");//错误
printPeople({name:'李四',age:26,sex:''});//错误

 

     可选接口:接口中的属性是可选的

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

function printPeople(person:IPeople) {
    console.log("姓名:"+person.name);
    console.log("年龄:"+person.age);
}

printPeople({name:'张三',age:25}); //正确
printPeople({name:'王五'}); //不传age也可以,但是接口中age后必须带?
printPeople("123");//错误
printPeople({name:'李四',age:26,sex:''});//错误

 

   2、函数类型接口:对方法传入的参数以及返回值进行约束

//加密的函数类型接口
interface encrypt {
    (key:string,value:string):string;
}

var md5:encrypt = function (key:string,value:string):string {

    return key+value;
}

console.log(md5('deyun','Web前端'))

 

3、可索引接口:对数组和对象的约束(不常用)

//对数组的约束
interface UserArr {
    [index:number]:string; //字符串类型数组,数组的索引为number类型
}

var arr: UserArr = ["12","李四","aaa"];//正确
var arr1: UserArr = [1,"李四",a]; //错误

//对对象的约束
interface UserObj {
    [index:string]:string;
}
var obj:UserObj = { "姓名":"张三","性别":"" }; //正确
var obj1: UserObj = []; //错误

 

  4、类类型接口:对类的约束

interface IAnimal {
    sleep(): void;
    eat(): void;
}
class Dog implements IAnimal{
    eat(): void {
        console.log("狗狗在吃肉...");
    }

    sleep(): void {
        console.log("狗狗在睡觉:呼呼...")
    }
}

 

二、接口继承:接口继承就是说接口可以通过其他接口来扩展自己。TypeScript 允许接口继承多个接口。继承使用关键字 extends。

   1、单接口继承语法格式:

     Child_interface_name extends super_interface_name

   示例:

interface Shape {

    color: string;

}

interface Square extends Shape {

    sideLength: number;

}

 

let square = <Square>{};

square.color = "blue";

square.sideLength = 10;

console.log(square)

     2、多接口继承语法格式:

Child_interface_name extends super_interface1_name

     示例:

interface Shape {

    color: string;

}

 

interface PenStroke {

    penWidth: number;

}

interface Square extends Shape, PenStroke {

    sideLength: number;

}

 

let square1 = <Square>{};

square1.color = "blue";

square1.sideLength = 10;

square1.penWidth = 5.0;

console.log(square1)

 

 

 

 

推荐阅读