接口只聲明成員方法,不做實(shí)現(xiàn)唁毒。
類聲明并實(shí)現(xiàn)方法蒜茴。
接口就是用于聲明函數(shù)的,然后在類中去實(shí)現(xiàn)這些接口里的函數(shù)浆西。
那么接口有什么用呢粉私?設(shè)想如下需求:
要實(shí)現(xiàn)一個(gè)print函數(shù),它將傳入的對(duì)象打印出來近零。在實(shí)際實(shí)現(xiàn)上诺核,它將調(diào)用對(duì)象的getContent方法:
function print(obj): void {
console.log(obj.getContent());
}
但是這樣書寫是有問題的,你知道Typescript當(dāng)中是有類型檢查的秒赤,必須要確保obj中存在getContent方法才能讓print函數(shù)正常工作不報(bào)錯(cuò)猪瞬。
比如:
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函數(shù)不就只能打印Article類的對(duì)象了嗎,如果我想要讓它能夠打印不止一個(gè)類的對(duì)象呢入篮?我如何保證他們都有g(shù)etContent方法陈瘦?
這時(shí)候就可以用到接口,來聲明一個(gè)getContent方法潮售,這樣一來痊项,每個(gè)實(shí)現(xiàn)該接口的類都必須實(shí)現(xiàn)getContent方法:
interface ContentInterface {
getContent(): String;
}
class Article implements ContentInterface {
// 必須實(shí)現(xiàn)getContent方法
public function getContent(): String {
return 'I am an article.';
}
}
class Passage implements ContentInterface {
// 但實(shí)現(xiàn)方式可以不同
public function getContent(): String {
return 'I am a passage.'
}
}
class News implements ContentInterface {
// 沒有實(shí)現(xiàn)getContent方法,編譯器會(huì)報(bào)錯(cuò)
}
function print(obj: ContentInterface): void {
// 實(shí)現(xiàn)了ContentInterface的對(duì)象是一定有g(shù)etContent方法的
console.log(obj.getContent());
}
let a = new Article();
let p = new Passage();
print(a); // "I am an article."
print(p); // "I am a passage."