工程師與貓
ESC
Content
    ↑↓ navigate open esc close
    Published on

    Typescript 學習筆記 - Section 6

    Authors
    • avatar
      Name
      Alex Yu

    Section Overview

    這章節主要會介紹如何使用 Tuples

    Tuples in Typescript

    定義: 類似於 array 的資料型態,只是在 aray 中的每個 element 代表著某一筆資料的某個屬性

    比如說,以下的資料代表一杯飲料的 object 型態

    {
      color: 'brown'
      carbonated: true,
      sugar: 40
    }

    如果今天以 array 的形式來表示值的時候變成

    ['brown', true, 40];

    這時候 array 中每個 element 的順序性就很重要,因為順序如果錯亂則 element 所代表的值就會失去意義

    Examples

    const drink = {
      color: 'brown'
      carbonated: true,
      sugar: 40
    }
     
    const pepsi: [string, boolean, number] = ['brown', true, 40]
     
    // will get ts error
    pepsi[0] =40
     
    // Type alias
    type Drink =  [string, boolean, number]
    const pepsi: Drink = ['brown', true, 40]
    const sprite: Drink = ['clear', true, 40]
    const tea: Drink = ['brown', false, 0]
     

    Why Tuples?

    假設我們今天看到一種資料

    const carSpecs: [number, number] = [400, 3354];

    光看上面這一行會很難以理解每個數字所代表的意義,但如果轉成 oject 類型就很容易理解

    const carStats = {
      horsepower: 400,
      weight: 3354,
    };

    因為 js object 的關係,在 object 裡面要一個 key 搭配一個 value,value 所代表的意義會透過 key 表示出來, 但有些時候我們所遇到的資料並不一定都會是以 object 型態呈現,這時候就需要 Tuples 來幫助表達資料代表的意義