TypeScript => 接口 interface

TypeScript笔记

6. TypeScript => 接口 interface

// ts => 接口 interface  类类型接口使用 implements

// 1. 属性类接口

// 2. 函数类型接口 对方法传入的参数 以及 返回值 进行约束
/*
interface encrypt {
    (key: string, value: string): string;
}

let md5: encrypt = function (key: string, value: string): string {
    return key + value;
}
console.log(md5('wang','lili'));
*/
// 3. 可索引接口 数组、对象的约束 (不常用)
/*
interface UserArr{
    [index:number]:any;
}
let arr:UserArr=[123,'llll'];
console.log(arr);
interface UserObj{
    [index:string]:any;
}
let obj:UserObj = {name:'lili',age:20,job:'web'}
console.log(obj)
*/
// 4. 类类型接口 对类的约束 和抽象类有点相似
/*
interface Animal{
    name:string;
    eat(str:string):any;
}
class Dog implements Animal {
    name:string;
    constructor(name:string){
        this.name = name;
    }
    eat(){
        console.log(`${this.name} is eat food`)
    }
}
let dog = new Dog('dog');
dog.eat();
*/
// 5.接口扩展 接口可以继承接口 
/*
interface Animal {
    eat(): void;
}
//继承
interface Person extends Animal {
    job: string;
    work(): void;
}

//定义一个抽象类
abstract class Programmer{
    public name:string;
    constructor(name:string){
        this.name = name;
    }
    // 定义一个抽象方法 只定义规则 不负责具体实现 由派生类、子类 实现
    abstract coding(code:string):void;
}

class Web implements Person {
    protected name: string;
    public job: string;
    constructor(name: string, job: string) {
        this.name = name;
        this.job = job;
    }
    eat() {
        console.log(`my name is ${this.name}`);
    }
    work() {
        console.log(`${this.name} is working  my work is ${this.job}`);
    }
}
//定义一个 Ts 类 继承 Programer抽象类 并使用 Person接口进行约束
class Ts extends Programmer implements Person{
    public job :string;
    constructor(name:string,job:string = "TS engineer"){
        super(name);
        this.job = job;
    }
    coding(code:string){
        console.log(`I'm ${this.name}.I'm a ${this.job}.I Write ${code} code every day`);
    }
    eat() {
        console.log(`my name is ${this.name}`);
    }
    work() {
        console.log(`${this.name} is working  my work is ${this.job}`);
    }
}
let laowang = new Ts('LaoWang');
laowang.coding('typescript');
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值