TypeScript學習3-接口

什麼是接口

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; // 可選屬性
}
  • 索引類型,支持string,number索引屬性
interface CustomerInfo {
  customerCode: string;
  customerName: string;
  customerAddr?: string; // 可選屬性
  [key: string]: any; // 其餘任意名稱,任意類型的屬性
}
這裏說明一下,由於JavaScript對象中,數字索引是會轉換成string來取值的。若是一個接口裏面,同時有number、string索引屬性時,number索引屬性的類型,必須時string索引屬性的子類型。 也就是,number索引的屬性類型,必須能被string索引的屬性類型覆蓋;用number索引去取值,取到的值也是string索引屬性的類型。

靜態屬性和只讀屬性

  • 靜態類型,即類屬性,static修飾
  • 只讀屬性,初始化後不能修改,readonly修飾
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

相關文章
相關標籤/搜索