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."    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM