typescript中接口和类的区别

ts中的接口

  1. 一般用来定义数据结构,因为ts中的interface不同于其它强类型语言的一点是,interface中可以定义变量,这就使得interface还可以充当一些model对象的基类使用,而并非通常的用来定义一些行为。
  2. 接口只声明成员方法,不做实现。

ts中的类

  1. 类声明并实现方法

场景

接口有什么用呢?设想如下需求:
要实现一个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."

你可能感兴趣的:(typescript,typescript,javascript,前端)