TypeScript 中的介面預設值

Muhammad Ibrahim Alvi 2023年1月30日
  1. TypeScript 中的介面是什麼
  2. 使用可選屬性在 TypeScript 中設定 Interface 預設值
TypeScript 中的介面預設值

本教程提供了另一種在 TypeScript 中定義 Interface 預設值的解決方案。它提供了編碼示例和輸出以及有關介面是什麼以及使用它們的原因的知識。

TypeScript 中的介面是什麼

TypeScript 有一個型別檢查的核心原則,它專注於值的形狀;有時,這稱為鴨子型別或結構子型別。TypeScript 中的介面扮演在程式碼內和專案外定義合約的角色。

以下是如何在 TypeScript 中定義 Interface

interface LabeledVal {
  label: string;
}

function printLabelTraces(labeledObject: LabeledVal) {
  console.log(labeledObject.label);
}

let myObject = { size: 10, label: "Size 10 Object" };
printLabelTraces(myObject);

上面的程式碼產生以下輸出。

預設介面輸出

這個介面描述了具有 label 屬性的要求,即一個字串。Interface LabeledVal 是一個名稱,我們可以用它來描述我們傳遞給 printLabelTraces 的物件實現的 Interface,就像我們在其他語言中可能擁有的那樣。

如果我們傳遞給函式的物件成功滿足介面中列出的要求,則它是允許的。

現在讓我們看看如何在 TypeScript 中定義 Interface 預設值。

使用可選屬性在 TypeScript 中設定 Interface 預設值

由於不需要所有屬性都存在於實現介面的物件中,因此 Optional Properties 是流行的選項,可用於提供類似模式的選項包,其中函式的物件僅填充了幾個屬性。考慮以下示例的一個程式碼。

interface SquareConfig {
  color?: string;
  width?: number;
}

function Square(config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: "white", area: 100 };
  if (config.color) {
    newSquare.color = config.color;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let SquareVal = Square({ color: "black" });

console.log(SquareVal);

在此程式碼中,SquareVal 從函式 Square 獲取返回值,該函式具有 interface``SquareConfig 的引數型別,它具有一個可選值,可以根據使用情況分配或不分配。上面的程式碼產生以下輸出。

可選屬性

使用可選屬性編寫介面的方式與使用 ? 編寫普通介面相同。在屬性名稱末尾的宣告中帶有可選屬性。這可以防止使用不屬於介面的屬性。

考慮 Squarecolor 屬性的錯誤名稱示例;我們會收到一條錯誤訊息。

// @errors: 2551
interface SquareConfig {
  color?: string;
  width?: number;
}

function Square(config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: "white", area: 100 };
  if (config.clor) {
    // Error: Property 'clor' does not exist on type 'SquareConfig'
    newSquare.color = config.clor;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let SquareVal = Square({ color: "black" });

錯誤輸入屬性名稱

沒有其他方法可以為介面或型別別名提供預設值,因為它們只是編譯時的,而對於預設值,我們需要執行時支援。上述可選屬性提供了該問題的替代解決方案。

Muhammad Ibrahim Alvi avatar Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn

相關文章 - TypeScript Interface