ts中interface与class的区别

interface -- 接口只声明成员方法,不做实现。

class -- 类声明并实现方法。

那么接口有什么用呢?设想如下需求:

要实现一个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."    

 

posted @ 2017-10-19 16:54  狂奔的小马扎  阅读(25354)  评论(0编辑  收藏  举报