TypeScript Interface的使用詳解

一、Interface基礎

1、Interface是什麼


interface Person {
  name: string;
  age: number;
}

上面的代碼定義了一個Person介面,它包含了兩個屬性name和age,分別為字元串類型和數字類型。

2、Interface的作用

Interface可以用來對對象、函數、類等進行類型檢查,同時也可以充當文檔,讓開發者清楚了解介面的使用方法和所期望的返回值類型。

3、Interface的繼承


interface Person {
  name: string;
  age: number;
}

interface Student extends Person {
  grade: number;
}

上面的代碼定義了一個Student介面,它繼承了Person介面,並且新增了一個grade屬性,為數字類型。

二、Interface的可選屬性和只讀屬性

1、可選屬性


interface Person {
  name: string;
  age?: number;
}

const person1: Person = { name: 'Alice' };
const person2: Person = { name: 'Bob', age: 20 };

上面的代碼中,age屬性在Person介面中被定義為可選屬性,意味著在對象實例化時可以選擇不傳入age屬性。

2、只讀屬性


interface Person {
  readonly name: string;
  age: number;
}

const person: Person = { name: 'Alice', age: 20 };
person.name = 'Bob'; // 編譯報錯,無法更改只讀屬性

上面的代碼中,name屬性在Person介面中被定義為只讀屬性,意味著該屬性無法被更改。

三、Interface的函數定義

1、函數類型


interface SearchFunc {
  (source: string, subString: string): boolean;
}

const mySearch: SearchFunc = function (source: string, subString: string) {
  return source.indexOf(subString) > -1;
};

上面的代碼定義了一個函數類型的介面SearchFunc,並且將其賦值給mySearch變數,該變數是一個函數,接收兩個字元串類型的參數,返回布爾類型的值。

2、可選參數和默認參數


interface BuildNameFunc {
  (firstName: string, lastName?: string): string; 
}

function getName(name: BuildNameFunc, firstName: string, lastName = 'Doe'): string {
  return name(firstName, lastName);
};

const fullName = getName(function(firstName, lastName) {
  return `${firstName} ${lastName}`;
}, 'John');
console.log(fullName); // John Doe

上面的代碼中,BuildNameFunc介面包含兩個參數,其中lastName是可選參數,可以不傳入,同時也可以設置默認值。getName函數接收一個函數類型的參數name,並且調用該函數返回字元串類型的值。

四、Interface的類定義

1、類類型實現介面


interface ClockInterface {
  currentTime: Date;
  setTime(d: Date): void;
}

class Clock implements ClockInterface {
  currentTime: Date = new Date();
  setTime(d: Date) {
    this.currentTime = d;
  }
  constructor(h: number, m: number) {}
}

上面的代碼中,定義了一個ClockInterface介面,包含了currentTime屬性和setTime方法。Clock類實現了該介面,並且實現了currentTime屬性的賦值和setTime方法的定義。

2、類類型介面


interface ClockConstructor {
  new(h: number, m: number): ClockInterface;
}
interface ClockInterface {
  tick(): void;
}
function createClock(ctor: ClockConstructor, h: number, m: number): ClockInterface {
  return new ctor(h, m);
}

class DigitalClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("beep beep");
  }
}
class AnalogClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("tick tock");
  }
}

const digital = createClock(DigitalClock, 12, 17);
const analog = createClock(AnalogClock, 7, 32);

上面的代碼中,定義了一個ClockConstructor介面,包含了new方法,該方法返回ClockInterface實例。createClock函數接收一個ClockConstructor類型的參數和兩個數字類型的參數,返回一個ClockInterface實例。DigitalClock和AnalogClock類實現了ClockInterface介面,並且傳遞給createClock函數用於實例化。

五、Interface的其他使用場景

1、索引類型


interface StringArray {
  [index: number]: string;
}

const arr: StringArray = ['Bob', 'Alice'];
const name: string = arr[0];

上面的代碼中,定義了一個StringArray介面,表示字元串類型的數組,方括弧內為索引類型,代表容器內元素的類型。

2、字元串字面量類型


interface Easing {
  easeIn: string;
  easeOut: string;
  easeInOut: string;
}

const easing: Easing = {
  easeIn: 'ease-in',
  easeOut: 'ease-out',
  easeInOut: 'ease-in-out'
};

上面的代碼中,定義了一個Easing介面,為字元串字面量類型,代表了三種不同的easing動畫類型。

3、混合類型


interface Counter {
  (start: number): string;
  interval: number;
  reset(): void;
}

function getCounter(): Counter {
  const counter = function (start: number) {} as Counter;
  counter.interval = 123;
  counter.reset = function() {};
  return counter;
}

const myCounter = getCounter();
myCounter(10);
myCounter.reset();
myCounter.interval = 5.0;

上面的代碼中,定義了一個Counter介面,是一個既可以像函數一樣使用,又可以包含屬性和方法的介面類型。

六、總結

通過本文的介紹,我們了解了TypeScript Interface在多種場景中的使用方式,從基本類型定義,到介面繼承、可選屬性和只讀屬性、函數類型定義、類類型實現介面、類類型介面、索引類型和混合類型,我們可以看到Interface的作用分布在TypeScript中的各個角落。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/304921.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-01 11:06
下一篇 2025-01-01 11:06

相關推薦

  • Linux sync詳解

    一、sync概述 sync是Linux中一個非常重要的命令,它可以將文件系統緩存中的內容,強制寫入磁碟中。在執行sync之前,所有的文件系統更新將不會立即寫入磁碟,而是先緩存在內存…

    編程 2025-04-25
  • 神經網路代碼詳解

    神經網路作為一種人工智慧技術,被廣泛應用於語音識別、圖像識別、自然語言處理等領域。而神經網路的模型編寫,離不開代碼。本文將從多個方面詳細闡述神經網路模型編寫的代碼技術。 一、神經網…

    編程 2025-04-25
  • git config user.name的詳解

    一、為什麼要使用git config user.name? git是一個非常流行的分散式版本控制系統,很多程序員都會用到它。在使用git commit提交代碼時,需要記錄commi…

    編程 2025-04-25
  • Java BigDecimal 精度詳解

    一、基礎概念 Java BigDecimal 是一個用於高精度計算的類。普通的 double 或 float 類型只能精確表示有限的數字,而對於需要高精度計算的場景,BigDeci…

    編程 2025-04-25
  • Python安裝OS庫詳解

    一、OS簡介 OS庫是Python標準庫的一部分,它提供了跨平台的操作系統功能,使得Python可以進行文件操作、進程管理、環境變數讀取等系統級操作。 OS庫中包含了大量的文件和目…

    編程 2025-04-25
  • Linux修改文件名命令詳解

    在Linux系統中,修改文件名是一個很常見的操作。Linux提供了多種方式來修改文件名,這篇文章將介紹Linux修改文件名的詳細操作。 一、mv命令 mv命令是Linux下的常用命…

    編程 2025-04-25
  • nginx與apache應用開發詳解

    一、概述 nginx和apache都是常見的web伺服器。nginx是一個高性能的反向代理web伺服器,將負載均衡和緩存集成在了一起,可以動靜分離。apache是一個可擴展的web…

    編程 2025-04-25
  • 詳解eclipse設置

    一、安裝與基礎設置 1、下載eclipse並進行安裝。 2、打開eclipse,選擇對應的工作空間路徑。 File -> Switch Workspace -> [選擇…

    編程 2025-04-25
  • MPU6050工作原理詳解

    一、什麼是MPU6050 MPU6050是一種六軸慣性感測器,能夠同時測量加速度和角速度。它由三個感測器組成:一個三軸加速度計和一個三軸陀螺儀。這個組合提供了非常精細的姿態解算,其…

    編程 2025-04-25
  • Python輸入輸出詳解

    一、文件讀寫 Python中文件的讀寫操作是必不可少的基本技能之一。讀寫文件分別使用open()函數中的’r’和’w’參數,讀取文件…

    編程 2025-04-25

發表回復

登錄後才能評論