typescript 接口 java_TypeScript 类实现接口

TypeScript类实现接口与C#或者Java等语言非常类似,用来强制一个类去符合某种契约。

代码实例如下:[typescript] 纯文本查看 复制代码interface Itest {

webName: string;

}

class Antzone implements Itest {

webName: "蚂蚁部落";

age:4;

constructor() { }

}

在TypeScript 接口简介一章节最后介绍过,接口只规定约束,并没有具体实现。

如果类实现某一接口,那么就可以实现接口中的成员,上面的代码中,将webName赋值为字符串"蚂蚁部落"。

又因为接口是描述数据的结构的,所以实现接口的类没必要实现接口中的成员。

代码实例如下:[typescript] 纯文本查看 复制代码interface Itest {

webName: string;

show(address: string);

}

class Antzone implements Itest {

webName;

age:4;

show(address:string){

console.log(address);

}

constructor() { }

}

上面的代码中,webName并没有被实现。

当一个类实现了一个接口时,只对其实例部分进行类型检查,代码实例如下:[typescript] 纯文本查看 复制代码interface Itest {

new (str: string, num: number):void;

}

class Antzone implements Itest {

constructor(strh: string, num: number) { }

}

接口规定了构造函数的签名,然而只会检查类的实例部分,所以类的构造函数不会被检测到。

报错截图如下:

223356dfjlfk9iuks2iffd.png

既然无法检测类的非实例部分,那么可以变通一下修改类的构造函数:[typescript] 纯文本查看 复制代码interface ClockConstructor {

new (hour: number, minute: number): ClockInterface;

}

interface ClockInterface {

tick();

}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {

return new ctor(hour, minute);

}

class DigitalClock implements ClockInterface {

constructor(h: number, m: number) { }

tick() {

console.log("beep beep");

}

}

class AnalogClock implements ClockInterface {

constructor(h: number, m: number) { }

tick() {

console.log("tick tock");

}

}

let digital = createClock(DigitalClock, 12, 17);

let analog = createClock(AnalogClock, 7, 32);

代码非常的简单,不多介绍,如果有任何疑问可以在文章底部留言。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值