0
点赞
收藏
分享

微信扫一扫

TypeScript-学不会的ts-4(接口)

mjjackey 2022-02-26 阅读 150

TypeScript-学不会的ts-4(接口)

TypeScript接口

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

接口类别

属性接口

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:'男'});//错误

函数类型接口

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

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

    return key+value;
}

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

可索引接口

//对数组的约束
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 = []; //错误

类类型接口

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

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

接口继承

单接口继承

语法格式:

  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)

多接口继承

语法格式:

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)
举报

相关推荐

0 条评论