[Typescript] Tuple types


🎯 Goals
  • tupleタイプの定義と特徴を理解します.
  • tupleタイプをいつ使うか知ることができます.
  • 定義#テイギ#
    要素数と要素タイプで配列されたアレイ.
    jsは異なるタイプの要素に含まれることを知っています.
    (実際、jsでは配列はインデックス番号をキーとするハッシュマッピングにすぎない)
    When to use?
  • 定義の要素数とタイプ定義の「tuple(レコード)」を使用する場合、
  • API定義では、属性名を柔軟に定義する必要はありません.
    ex) React's useState const [error, setError] = useState(null);
  • 設計図と同時に任意に属性を命名する場合、
  • 固定された属性名とオブジェクト単位を使用する必要がある場合、次のコードは構造化されたモードです.
    Object Version
    interface Point {
        x: number;
        y: number;
    }
    
    const point1 : Point = {x: 5, y: 3};
    
    // { x: 5, y: 3 }
    console.dir(point1);
    
    これでどうですか.
    Tuple version
    type TuplePoint = [number, number, number?];
    const [x, y, z] : TuplePoint = [10, 12];
    
    // x: 10, y: 12, z: undefined
    console.log(`x: ${x}, y: ${y}, z: ${z}`);
    
    
    違いは、pointは客体であり、resultTypeは配列である.
    また、destructuringの場合、プロパティの名前は元のオブジェクトのpropertyと一致する必要はありません.また、spread、optional typeを設定することもできます.
    上記の例では、z座標がなくても大丈夫です.
    また,Promise.allのすべての結果値を一括して取り戻す場合にも用いられる.
    Promise.all
    (async ()=>{
        const [name, age, date] = await Promise.all([
            Promise.resolve('falcon'),
            Promise.resolve(33),
            Promise.resolve(new Date())
        ]);
    
      // falcon 33 2021-09-09T07:34:24.060Z
        console.log(name, age, date)
    })();
    
    🔗 Reference
  • Typescript document
  • powerful tuple types - git connected