TypeScript的核心就是類型檢查,接口就是用於聲明類型,給內部或第三方使用者提供類型聲明和約束。typescript
// 聲明數據類型 interface CustomerInfo { customerCode: string; customerName: string; } // 使用數據類型 function helloCustomer(customerInfo: CustomerInfo) { console.log(`Hello, ${customerInfo.customerName}!`); } helloCustomer({customerCode: '1001', customerName: 'Jee'}); // ok helloCustomer({customerName: 'Jee'}); // error, Property 'customerCode' is missing
這裏和麪向對象語言相似,用於定義對象接口,聲明對象的結構,定義類時能夠實現接口,知足這個接口定義的功能。編程
// 接口聲明 interface Animal { name: string; } // 接口繼承 interface Mammal extends Animal { legNum: number; sound(): string; } // 類實現 class Bull implements Mammal { name: string; legNum: number; constructor(name: string) { this.name = name; this.legNum = 4; } sound() { return 'moo'; } } // 實例 let bull1 = new Bull('bull1'); console.log(bull1.sound()); // moo
有兩種方式能夠實現可變屬性,屬性明確時,推薦第一種。不明確時能夠用第二種。函數
interface CustomerInfo { customerCode: string; customerName: string; customerAddr?: string; // 可選屬性 }
interface CustomerInfo { customerCode: string; customerName: string; customerAddr?: string; // 可選屬性 [key: string]: any; // 其餘任意名稱,任意類型的屬性 }
這裏說明一下,由於JavaScript對象中,數字索引是會轉換成string來取值的。若是一個接口裏面,同時有number、string索引屬性時,number索引屬性的類型,必須時string索引屬性的子類型。 也就是,number索引的屬性類型,必須能被string索引的屬性類型覆蓋;用number索引去取值,取到的值也是string索引屬性的類型。
interface CustomerInfo { static greeting = 'Hello'; // 靜態屬性 static readonly standardGreeting = 'Hello'; // 只讀靜態屬性 readonly customerCode: string; // 只讀屬性 customerName: string; // 普通屬性 }
const vs readonly,變量用const,屬性用readonly
接口除了能描述對象類型,還能描述函數類型(這個和麪向對象語言有點不同,須要理解一下)。學習
interface SearchFunc { (content: string, key: string): boolean; } // 這裏參數名能夠不同,類型也能夠省略 let mySearchFunc: SearchFunc = (c, k) => { return c.search(k) > -1; }
會再寫一遍類的學習,一篇接口與類的結合使用。this