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?

More than 1 year has passed since last update.

TypeScriptのオブジェクトから邪魔なキーを動的に消す

0
Posted at

TypeScriptにはPickだとかOmitだとか便利な型ユーティリティが組み込みでありますが、あれらじゃ足りないことがたまにあります。
例えば、eから始まるキーだけ抽出したいとか。

そういうときはmapped typesでキーを再マッピングしましょう。

/**
* プロパティの名前が`e`で始まるエントリだけ抽出します。
*/
type PickElegantEntry<R extends Record<PropertyKey, unknown>> = {
    [k in keyof R as `${k extends `e${string}` ? r : never }`]: R[k]
}

面白いことに、再マッピングでneverを返すとそのキーについては除外されます。なので、出力はこうなります:

type RushE = PickElegantEntry<{
    elegant: 1,
    notElegant: "excluded!",
    elephant: 2,
    electricity: 3
}>;

const eeeeee: RushE = { elegant: 1, elephant: 2, electricity: 3 };
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?