Skip to content

Instantly share code, notes, and snippets.

@nasheomirro
Last active December 28, 2023 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasheomirro/c8c8c25da0803e7515fc6c2cf7c5b2c8 to your computer and use it in GitHub Desktop.
Save nasheomirro/c8c8c25da0803e7515fc6c2cf7c5b2c8 to your computer and use it in GitHub Desktop.
A utility to flatten keys just like how react-hook-form does it
type FlattenKeys<T extends Record<string, any>, prefix extends string = ''> = {
[key in keyof T]: key extends string
? T[key] extends object
? `${prefix}${key}` | FlattenKeys<T[key], `${prefix}${key}.`>
: `${prefix}${key}`
: never;
}[keyof T];
// and to use it:
type Data = {
title: string;
meta: {
dateCreated: string;
author: {
username: string;
userId: string;
};
};
};
// "title" | "meta" | "meta.author" | "meta.author.userId" | ...
type Keys = FlattenKeys<Data>;
// for arrays being inside, you need to remove their types from the union
type RemoveNonString<T> = T extends string ? T : never;
type FixedData = RemoveNonString<FlattenKeys<Data>>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment