typescript中的 接口

typescript中接口的作用: 在面向对象的编程中,接口是一种规范的定义,他定义了行为和动作的规范,在程序设计里面,接口起到批量约束和定义标准的作用

一、接口对属性的约束

interface Person {
    name: string,
    age: number
}

function male(p: Person) {
    p.name;
    console.log(p.name, p.age)
}
// 由于函数定义了Person的接口,限制属性值和属性类型,且传入的类型为对象

// 方式一:传入的参数:这种直接传入参数的方法只能传入接口中固定的属性,不能增加
male({name: "alex", age: 18})
// 方式二:在函数外定义好对象,只需保证对象有自己需要的属性即可,允许有多余属性
var personOne = {
    name: "tom",
    age: 16,
    gender: "male"
}
male(personOne) // 没报错,可正常运行

// 接口对属性的约束实例:使用接口实现ajax

/*
    $.ajax({
        type: "GET",
        url: "test.json",
        data: {username: $("#username").val()}  // ajax请求所携带的请求数据
        dataType: "json"
    });
*/

interface Config {
    type: string;
    url: string;
    data?: string;
    dataType: string;
}
import { XMLHttpRequest } from "XMLHttpRequest" // ts中无XMLHttpRequest模块,需得自己编写声明文件
function ajax (config: Config) {
    var xhr = new XMLHttpRequest();
    xhr.open(config.type, config.url, true) //这里的true表示异步
    xhr.send(config.data);
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200) {
            console.log("success");
            // 这里成功后判断发送数据的类型,如果是json就转为字符串
            if(config.dataType === "json") {
                JSON.parse(xhr.responseText)
            } else {
                console.log(xhr.responseText)
            }
        }
    }
}

ajax({
    type: "GET",
    data: "name = tom",
    url: "http://www.weather.com.cn/data/cityinfo/101010100.html",
    dataType: "json"
})

二、接口对函数的约束:对参数和返回值进行批量约束
定义接口,指定函数能接受的参数类型以及返回值类型

interface Function {
    (key: string, value: string): void
}

// 接口对函数的约束
    // 注意: 函数类接口不同于属性类接口,要求属性的变量相同,这里变量可以不同,只需要保证变量的类型为string就行
var func1: Function = function(key: string, name: string) {
    console.log(key, name)
}
func1("hello", "world")

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

// 可索引接口(对对数组进行约束)
interface Arr {
    // 定义数组索引的类型,以及数组内的值类型
    [index: number]: string;
}

var array: Arr = ["hello", "wollens"];  // 正确
console.log(array[1])
var array1: Arr = [666, 777]    // 报错


// 对对象进行约束
interface Object {
    // 定义:索引值为字符串,值为字符串
    [index: string]: string;
}

// 生成的对象里的元素必须都是字符串类型
var obj: Object = {
    name: "wollens",
    gender: "male"
}

console.log(obj.name)

// 对类进行约束
interface Animal {
    // 定义类的name属性值
    name: string;
    // 定义类中的方法
    eat(name: string, gender: string): void
}

class Dog implements Animal {
    name: string;
    constructor(name: string){
        this.name = name;
    };
    // 注意接口定义的方法有参数,当你不传也不会报错
    eat() {
        console.log("defind success")
    }
}

var dog = new Dog("pika")
dog.eat()

class Cat implements Animal {
    name: string;
    constructor(name: string){
        this.name = name;
    };
    eat(name: string, gender: string) {
        console.log(`${this.name} is ${gender} cat like eat ${name}`)
    }
}
var cat = new Cat("herry")
cat.eat("fish", "male")

四、接口的拓展、继承

// 定义动物的接口
interface Animal {
    name: string;
    say(): void;
}
// 定义人的接口继承动物
interface Person extends Animal{
    gender: string;
    eat(food: string): void
}

// 创建一个类引用Person的接口
class Male implements Person {
    name: string;
    gender: string;
    constructor(name: string, gender: string) {
        this.name = name;
        this.gender = gender
    }

    say() {
        console.log(`hello ${this.name}`)
    }

    eat(food: string) {
        console.log(`${this.name} like ${food}`)
    }
}

var wollens = new Male("wollens", "male");
wollens.say();
wollens.eat("fish")

// 实现一个类继承 + 接口继承
class Child extends Male implements Person {
    age: number;
    constructor(name: string, gender: string, age:number) {
        super(name, gender);
        this.age = age;
    }

    say() {
        console.log(`hello ${this.name}`)
    }

    eat(food: string) {
        console.log(`${this.name} like ${food}`)
    }    
}

var body = new Child("Mile", "male", 12);
body.say();
body.eat("milk");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值