🐢

TypeScriptのタプルを知ろう

に公開

概要

別記事を書くにあたりタプルを理解しようの会

タプル型とは

配列のうち、要素の数と各要素の型を固定した型。
参考: https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types

配列の型定義だと string[]number[]、要素の型が異なる場合は any[] のように指定した。
が、このタプル型で指定することで配列の要素数やその要素ごとの型を定義しより縛りを強くし安全性を保つことができる。

type Hoge = any[];
// ↑異なる型の要素を持つ指定方法  ↓こちらにすることで安全性を強化
type Hoge = [string, number, boolean];

タプルとは

異なった型の要素を持つ配列
タプル型によって定義される配列。

type Hoge = [string, number, boolean];

const hoge: Hoge = ["ほげ太郎", 1, true]; // ✅OK
const fuga: Hoge = ["ほげ太郎", 1]; // 🚫要素数があっていないのでNG
const piyo: Hoge = ["ほげ太郎", 1, "true"]; // 🚫3つ目の要素の型があっていないのでNG
const hogera: Hoge = ["ほげ太郎", true, 1]; // 🚫要素の順番が型とあっていないのでNG

基本的に

  • TypeScriptにおいては要素の型が異なる配列を作ることをできる
  • その配列に限り「タプル」、その配列を定義する型を「タプル型」と呼んでいる

と覚えておけばOKそう。

タプルのtypeof

constで定義したタプルに対してのtypeofは以下のようになる。

const hoge = ['ほげ太郎', 1, true];
const fuga = ['ほげ太郎', "1", "true"];

type Hoge = typeof hoge; // [string, number, boolean]
type Fuga = typeof fuga; // string[]
type Piyo = (typeof hoge)[number]; // string | number | boolean
type Hogera = (typeof fuga)[number]; // string

as constを使った場合はこんな感じ。

const hoge = ["ほげ太郎", 1, true] as const;
const fuga = ["ほげ太郎", "1", "true"] as const;

type Hoge = typeof hoge; // ['ほげ太郎', 1, true]
type Fuga = typeof fuga; // ['ほげ太郎', "1", "true"]
type Piyo = (typeof hoge)[number]; // "ほげ太郎" | 1 | true
type Hogera = (typeof fuga)[number]; // "ほげ太郎" | "1" | "true"

タプルのkeyof

タプルに対してのkeyofは以下のようになる。

const hoge = ["ほげ太郎", 1, true];
type Hoge = keyof typeof hoge; // number

厳密にはhogeの要素のインデックスのリテラル型 0 | 1 | 2 と配列のインデックス numberユニオン型である 0 | 1 | 2 | number っぽいのだが
リテラル組が入っていることをうまく証明できなかったので一旦numberと書いている。

これはas constを使っていても同様。

const hoge = ["ほげ太郎", 1, true] as const;
type Hoge = keyof typeof hoge; // number

Discussion