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?

任意のT型に含まれるobjectを再帰的に調べ、それら全てを含むunion型(共用体)を作るメタ関数

Last updated at Posted at 2024-07-08

最近TypeScriptを使うようになったので備忘録。
下記のメタ関数はarray.flatmap()と似ており、ネストしたオブジェクトの中からobjectを全て取り出す。

type ReomoveArray<T> = T extends unknown[] ? T[number] : T;

type ExtractObject<T> = Extract<ReomoveArray<T>, object>;

type Pack<T> = (x: T) => void;

export type FlatObject<T> = T extends object
  ? Pack<T> | FlatObject<ExtractObject<T[keyof T]>>
  : never;

上記の内容でメタ関数を作成できる。
使い方は以下の通り。

export interface Person {
  name: string;
  age: number;
}
export interface Family {
  member: Person[];
  address: string;
}
//FlatObject<Family> と書いた場合、それはPack<Family> | Pack<Person>になる。

本当は[Family,Person]が欲しかったのだが、複雑そうなので取りやめ。
タプルで取得する方法自体は存在するので、時間がある時に再チャレンジするかもしれない。

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?