首頁 >web前端 >js教程 >理解打字稿記錄類型的綜合指南

理解打字稿記錄類型的綜合指南

Joseph Gordon-Levitt
Joseph Gordon-Levitt原創
2025-02-08 11:03:10186瀏覽

A Comprehensive Guide to Understanding TypeScript Record Type

本指南探討了Typescript'sRecord類型,這是一種用於創建具有一致價值類型的對象的強大工具。我們將介紹其定義,語法,與元素的比較,詳盡的案例處理和枚舉映射等實用應用,以及與Partial>,Pick的實用程序類型的高級用途。 Readonly

理解

> Record類型可讓您定義所有值共享相同類型的對像類型,而鍵可能會變化。 它的定義是:

Record

:字符串文字的結合或從聯合派生的類型,定義可能的鍵。
<code class="language-typescript">Record<keys type></keys></code>
>
  • :與密鑰關聯的所有值的類型。 Keys>
  • 例如,Type創建一個對象,其中每個鍵是字符串,每個值都是數字。 >

vs.Record<string number></string>

Record兩者都處理數據收集,但有很大差異:Tuple

    :具有固定值類型的命名屬性。 鍵值映射的理想選擇。
  • > Record
  • :訂購元素列表,每個元素都可能具有不同的類型。 對於固定尺寸的集合很有用。
  • Tuple>示例:

basic

用法
<code class="language-typescript">// Record: string keys, number values
type AgeMap = Record<string number>;

// Tuple: string and number in specific order
type Person = [string, number];</string></code>

定義ARecord涉及指定密鑰和值類型:>

實用應用Record

<code class="language-typescript">// Object with string keys and string values
type User = Record<string string>;</string></code>

> 詳盡的案例處理:

>確保所有枚舉或工會的案例都已處理:
  1. >

    通用類型檢查:
    <code class="language-typescript">enum Status { Pending, Completed, Failed }
    const statusMessages: Record<status string> = {
      [Status.Pending]: "Request pending...",
      [Status.Completed]: "Request complete!",
      [Status.Failed]: "Request failed."
    };</status></code>
    創建可重複使用的函數,生成記錄:
  2. 枚舉數據映射:
    <code class="language-typescript">function createRecord<k extends string t>(keys: K[], value: T): Record<k t> {
      return keys.reduce((acc, key) => ({ ...acc, [key]: value }), {});
    }</k></k></code>
    從枚舉創建查找表:
  3. >查找表:
    <code class="language-typescript">enum Color { Red, Green, Blue }
    const colorHex: Record<color string> = {
    };</color></code>
    有效地將鍵映射到值:
  4. 迭代
    <code class="language-typescript">type CountryCode = "US" | "CA";
    interface CountryInfo { name: string; }
    const countries: Record<countrycode countryinfo> = {
      US: { name: "United States" },
      CA: { name: "Canada" }
    };</countrycode></code>
    >
  5. 幾種方法允許迭代:

Record:迭代在鑰匙值對上。 >

:迭代在鍵上。

  • :返回一個鍵的數組。 Object.entries()
  • :返回一個值數組。 for...in>
  • 用實用程序類型的高級用法
  • Object.keys()
  • 與其他實用程序類型組合Object.values()>將其功能增強:>

Record

:創建不變的對象:
  • <code class="language-typescript">Record<keys type></keys></code>

  • Record結論

類型是打字稿中的寶貴資產,它提供了一種簡潔而安全的方法來管理具有一致價值類型的對象。 它的靈活性與其他實用程序類型相結合,允許創建可靠和可維護的代碼。 要進一步探索,請諮詢官方的打字稿文檔和其他資源。

以上是理解打字稿記錄類型的綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn