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?

keyofの舞踏会🕊️ 型システムを優雅に操るために

Posted at

keyofとは?

まぁ!お聞きになりまして?
keyof とは、オブジェクト型のキー(プロパティ名)の集合を取得する優雅な演算子ですわ。

type Person = {
    name: string;
    age: number;
};

type Keys = keyof Person; // "name" | "age"

keyof Person といたしますと、"name" | "age" というユニオン型を形成いたしますのよ。


Mapped Types(マップ型)の振る舞い

keyof を活用いたしますと、動的に型定義を優雅に行うことができますわ。

type MyReadOnly<T> = {
    readonly [K in keyof T]: T[K];
}

これは、T 型のすべてのプロパティを反復処理し、各プロパティ K に対し readonly を付与する仕組みですの。


具体的なイメージ

type ReadOnly<T> = {
    readonly [K in keyof T]: T[K]
}

type Person = {
    name: string;
    age: number;
};

type ReadOnlyPerson = MyReadOnly<Person>;

コンパイル時には以下のように展開されますわ。

type ReadOnlyPerson = {
    readonly name: string; // ここで T[K] が string になりますわ
    readonly age: number; // ここで T[K] が number になりますわ
}

淑女を悩ませるポイント

  • in 演算子の挙動
    • オブジェクトのキーをひとつずつ取り出して処理いたしますの
    • for...in ループの概念に近うございますわ
  • 抽象的な型操作のイメージが掴みにくい
    • まるで迷宮のような型の世界…ですが、一歩ずつ優雅に理解してまいりましょうね

まとめ

  • keyof T は、T のキーをユニオン型として取得いたしますの
  • K in keyof T は、KT のキーをひとつずつ取り出す仕組みですわ
  • T[K] は、キー K に対応する型を取得いたしますのよ

まぁ、これで keyof の世界も優雅に攻略できますわね!ふふっ🎀

問題

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?