[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>ts中的接口
*
一般用来定义数据结构,因为ts中的interface不同于其它强类型语言的一点是,interface中可以定义变量,这就使得interface还可以充当一些model对象的基类使用,而并非通常的用来定义一些行为。
* 接口只声明成员方法,不做实现。
<>ts中的类
* 类声明并实现方法
<>场景
接口有什么用呢?设想如下需求:
要实现一个print函数,它将传入的对象打印出来。在实际实现上,它将调用对象的getContent方法:
function print(obj): void { console.log(obj.getContent()); }
但是这样书写是有问题的,你知道Typescript当中是有类型检查的,必须要确保obj中存在getContent方法才能让print函数正常工作不报错。
比如:
class Article { public function getContent(): String { return 'I am an
article.'; } } function print(obj: Article): void { console.log(obj.getContent()
); } let a = new Article(); print(a);
但是这样的话print函数不就只能打印Article类的对象了吗,如果我想要让它能够打印不止一个类的对象呢?我如何保证他们都有getContent方法?
这时候就可以用到接口,来声明一个getContent方法,这样一来,每个实现该接口的类都必须实现getContent方法:
interface ContentInterface { getContent(): String; } class Article implements
ContentInterface { // 必须实现getContent方法 public function getContent(): String {
return 'I am an article.'; } } class Passage implements ContentInterface { //
但实现方式可以不同 public function getContent(): String { return 'I am a passage.' } }
class News implements ContentInterface { // 没有实现getContent方法,编译器会报错 } function
print(obj: ContentInterface): void { // 实现了ContentInterface的对象是一定有getContent方法的
console.log(obj.getContent()); } let a = new Article(); let p = new Passage();
print(a); // "I am an article." print(p); // "I am a passage."