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?

ネストしたObjectからキーを全て取得するユーティリティ型

Posted at
type Maybe<T> = T | null | undefined;
type NestedKeyOf<T extends Record<string, unknown>> = {
  [K in keyof T & string]: T[K] extends Maybe<Record<string, unknown>>
    ? T[K] extends Maybe<Record<string, unknown>>
      ? `${K}.${NestedKeyOf<NonNullable<T[K]>>}`
      : K
    : K;
}[keyof T & string];

以下の User 型を与えてみる

type User = {
  id: string;
  name: string;
  age?: number | null;
  category: string;
  email: string;
  address?: {
    city: string;
    country: string;
  } | null;
};

image.png

参考: https://medium.com/xgeeks/typescript-utility-keyof-nested-object-fa3e457ef2b2

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?