如何在TypeScript中使用Record型別?


在TypeScript中,Record型別是一個強大的工具,允許您定義具有特定鍵和相應值型別的物件型別。本教程將指導您學習使用Record型別的基礎知識,並沿途提供語法解釋和實際示例。無論您是初學者還是已經熟悉TypeScript,本教程都將幫助您瞭解如何在專案中有效地利用Record型別。

語法

在TypeScript中建立Record型別的語法很簡單。型別定義以關鍵字Record開頭,後跟尖括號(<>),其中包含用花括號({})括起來的鍵和值型別。以下是一個說明語法的示例:

type MyRecord = Record<string, number>;

在這裡,我們將MyRecord定義為一個Record型別,具有字串鍵和數字值。現在,讓我們深入研究Record型別有用的不同場景。

示例1:定義字典

Record型別的常見用例是建立具有特定鍵值對的字典。當您需要組織資料或按其各自的鍵訪問值時,這尤其有用。在此程式碼片段中,我們將AnimalAges定義為一個Record型別,具有字串鍵和數字值。ages物件代表我們的字典,動物名稱作為鍵,它們各自的年齡作為值。我們可以使用點表示法訪問值,如console.log語句所示。

type AnimalAges = Record<string, number>;
const ages: AnimalAges = {
   dog: 5,
   cat: 3,
   rabbit: 2,
};
console.log(ages.dog);
console.log(ages.cat);

編譯後,它將生成以下JavaScript程式碼:

var ages = {
   dog: 5,
   cat: 3,
   rabbit: 2
};
console.log(ages.dog);
console.log(ages.cat);

輸出

以上程式碼將產生以下輸出:

5
3

示例2:保留鍵型別

Record型別很靈活,允許您保留特定的鍵型別,例如字面量型別。當在物件中強制執行嚴格的鍵名時,這很有用。在此示例中,我們將FruitColors定義為表示不同水果名稱的聯合型別。然後,我們使用Record型別建立ColorsRecord,水果名稱作為鍵,字串值代表它們各自的顏色。透過使用字面量型別,我們確保只有有效的水果名稱可以用作colors物件中的鍵。

type FruitColors = 'apple' | 'banana' | 'orange'; type ColorsRecord = Record<FruitColors, string>;
const colors: ColorsRecord = {
   apple: 'red',
   banana: 'yellow',
   orange: 'orange',
};

console.log(colors.apple); 
console.log(colors.banana);

編譯後,它將生成以下JavaScript程式碼:

var colors = {
   apple: 'red',
   banana: 'yellow',
   orange: 'orange'
};
console.log(colors.apple);
console.log(colors.banana);

輸出

以上程式碼將產生以下輸出:

red
yellow

示例3:對映和轉換值

Record型別也可用於對映和轉換物件中的值。讓我們考慮一個場景,我們有一列學生姓名,並希望使用Record型別將其轉換為大寫。在此示例中,我們將StudentNames定義為具有特定鍵的物件型別,這些鍵表示學生姓名。然後,我們使用Record型別建立UppercaseNames,確保鍵與StudentNames中的鍵相同。透過使用toUpperCase()方法,我們將名稱轉換為大寫並將它們分配給uppercaseStudents物件中相應的鍵。

type StudentNames = {
   alice: string;
   bob: string;
   charlie: string;
};

type UppercaseNames = Record<keyof StudentNames, string>;

const students: StudentNames = {
   alice: 'Alice',
   bob: 'Bob',
   charlie: 'Charlie',
};

const uppercaseStudents: UppercaseNames = {
   alice: students.alice.toUpperCase(),
   bob: students.bob.toUpperCase(),
   charlie: students.charlie.toUpperCase(),
};

console.log(uppercaseStudents);

編譯後,它將生成以下JavaScript程式碼:

var students = {
   alice: 'Alice',
   bob: 'Bob',
   charlie: 'Charlie'
};
var uppercaseStudents = {
   alice: students.alice.toUpperCase(),
   bob: students.bob.toUpperCase(),
   charlie: students.charlie.toUpperCase()
};
console.log(uppercaseStudents);

輸出

以上程式碼將產生以下輸出:

{ alice: 'ALICE', bob: 'BOB', charlie: 'CHARLIE' }

示例4:處理動態物件鍵

當處理具有動態鍵的物件時,Record型別尤其有用。考慮一個場景,我們想計算句子中單詞的出現次數。在此示例中,我們定義countWords函式,該函式接受句子作為輸入並返回Record型別,其中鍵代表句子中唯一的單詞,值代表每個單詞出現的頻率。透過將句子拆分為單詞陣列並遍歷每個單詞,我們可以相應地更新wordCount物件中的計數。

function countWords(sentence: string): Record<string, number> {
   const words: string[] = sentence.split(' ');
   const wordCount: Record<string, number> = {};

   words.forEach((word) =< {
      if (wordCount[word]) {
         wordCount[word]++;
      } else {
         wordCount[word] = 1;
      }
   });

   return wordCount;
}

const sentence = 'This is a sentence. This sentence contains multiple words.';
const wordCount = countWords(sentence);

console.log(wordCount);

編譯後,它將生成以下JavaScript程式碼:

function countWords(sentence) {
   var words = sentence.split(' ');
   var wordCount = {};
   words.forEach(function (word) {
      if (wordCount[word]) {
         wordCount[word]++;
      }
      else {
         wordCount[word] = 1;
      }
   });
   return wordCount;
}
var sentence = 'This is a sentence. This sentence contains multiple words.';
var wordCount = countWords(sentence);
console.log(wordCount);

輸出

以上程式碼將產生以下輸出:

{
   This: 2,
   is: 1,
   a: 1,
   'sentence.': 1,
   sentence: 1,
   contains: 1,
   multiple: 1,
   'words.': 1
}

結論

TypeScript中的Record型別提供了一種方便的方法來定義具有特定鍵值對的物件。無論您是建立字典還是保留鍵型別,Record型別都提供靈活性和型別安全。透過理解語法並探索各種場景,您可以利用Record型別的強大功能來編寫更具表現力和更無錯誤的程式碼。

更新於:2023年8月21日

379 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.