接口Interface:用來建立某種代碼約定,使得qita開發(fā)者在調(diào)用某個方法或創(chuàng)建新的類時必須遵循接口所定義的代碼約定。
No 1:用接口聲明屬性
當(dāng)接口用作方法的參數(shù)的類型聲明,當(dāng)調(diào)這個方法的時候,TS會去檢查你傳入的參數(shù)是否符合接口的約定
interface Eat{
? ?name: string;
? ?price: number;
};
class Sheep{
? ? constructor(public config: Eat) {}
};
var p1 = new Sheep();? ? //報錯
var p2 = new Sheep('xxj',18); ? //報錯
var p3 = new Sheep({
? ? ?name: 'xxj',
? ? ?price:18
}); ? ? //正確調(diào)用方法:傳入一個帶有規(guī)定屬性的對象
No 2:對方法進(jìn)行約束
對方法進(jìn)行約束需要用到implements關(guān)鍵詞,它規(guī)定被約束的方法內(nèi)必須實現(xiàn)接口中的函數(shù)
interface ?Animal{
? ?eat();
};
class Sheep implements Animal {
? eat (){ console.log("grass"); }
};