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;
};
参考: https://medium.com/xgeeks/typescript-utility-keyof-nested-object-fa3e457ef2b2