0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】タプルからオブジェクトを生成(type-challenges No.3)

Last updated at Posted at 2024-12-04

お題

タプルを受け取り、その各値のkey/valueを持つオブジェクトの型に変換する型を実装する。

やりたいこと(具体)

const tuple = ["A", "B", "C", "D"] as const
type reault = TupleToObject<T>

// expected { "A":"A", "B":"B", "C":"C", "D":"D" }

解答

type TupleToObject<T extends readonly any[]> = {
  [V in T[number]]:V
}

解説

処理の流れ

  • <T extends readonly any[]>
    Tは読み取り専用の配列のみに制約。
    → 単純な配列の型ではなく、配列の具体的な中身を受け取りたいから。
  • [V in T[number]]
    配列の中身を全てユニオン型で取得
  • { [V in T[number]]:V }
    Mapped Typesでオブジェクトを生成。

そもそもタプルとは...

  • 特定の型と順序を持つ要素の集まり。
    配列とは異なり、各要素の型を個別に指定できる。
const Person:[string, number] = ["Tom", 20]
// 1番目は文字列、2番目は数値と固定された構造

constアサーション(as const)とは...

  • オブジェクト・配列の末尾にas constと記述することにより、全ての値をreadonly(読み取り専用)にする。
  • ネストされたオブジェクトに対しても、全ての値がreadonlyになる。
const color = ["red", "blue", "green", "yellow", "purple"] as const;
// readonly ["red", "blue", "green", "yellow", "purple"]

typeof演算子とは...

  • 変数から型を抽出する型演算子。
typeof "Hello World"; // => "string"
typeof 0; // => "number"
typeof true;  // => "boolean"

const Person = {
  name: "Tom",
  age: 20
};
typeof Person; // => { name: string, age: number };

const color = ["red", "blue", "green", "yellow", "purple"];
typeof color // => string[]

[number]とは...

  • 全てのインデックスの要素の型を、ユニオン型で抽出する。
const color = ["red", "blue", "green", "yellow", "purple"] as const;
type result = (typeof color)[number];

// expected "red" | "blue" | "green" | "yellow" | "purple"

Mapped Typesとは...

「復習:Pickの自作(TC-1)」参照
https://www.refty.jp/yuto99999/cm42vg7kb0001f8juia24wuht

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?