Last active
August 8, 2024 05:44
-
-
Save jlucaso1/220756deaa75d130306bdece460d4c61 to your computer and use it in GitHub Desktop.
This TypeScript code snippet provides a function prefixKeys that allows you to prefix all the keys of an object or array of objects with a specified string. It also defines helper types to ensure type safety throughout the process.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // @author: https://github.com/jlucaso1 | |
| // @url: https://gist.github.com/jlucaso1/220756deaa75d130306bdece460d4c61 | |
| type ObjectUnion = Record<string, unknown> | unknown; | |
| const isObject = (value: unknown): value is Record<string, unknown> => | |
| typeof value === 'object' && | |
| value !== null && | |
| !(value instanceof RegExp) && | |
| !(value instanceof Error) && | |
| !(value instanceof Date); | |
| interface Options<Prefix extends string = string> { | |
| prefix: Prefix; | |
| } | |
| export function prefixKeys< | |
| T extends ObjectUnion | ReadonlyArray<Record<string, unknown>>, | |
| Prefix extends string, | |
| >(input: T, options: Options<Prefix>): PrefixKeys<T, Options<Prefix>> { | |
| if (Array.isArray(input)) { | |
| return input.map((element) => prefixKeys(element, options)) as PrefixKeys< | |
| T, | |
| Options<Prefix> | |
| >; | |
| } | |
| return transform(input, options) as PrefixKeys<T, Options<Prefix>>; | |
| } | |
| function transform(input: unknown, options: Options<string>): unknown { | |
| if (!isObject(input)) { | |
| return input; | |
| } | |
| const { prefix } = options; | |
| const result: Record<string, unknown> = {}; | |
| for (const key in input) { | |
| if (Object.prototype.hasOwnProperty.call(input, key)) { | |
| const value = input[key]; | |
| result[`${prefix}${key}`] = value; | |
| } | |
| } | |
| return result; | |
| } | |
| type PrefixKeys< | |
| T extends ObjectUnion | ReadonlyArray<Record<string, unknown>>, | |
| O extends Options<string>, | |
| > = | |
| T extends ReadonlyArray<Record<string, unknown>> | |
| ? Array<PrefixKeys<T[number], O>> | |
| : T extends Record<string, unknown> | |
| ? { | |
| [K in keyof T as K extends string | |
| ? `${O['prefix']}${K}` | |
| : never]: T[K]; | |
| } | |
| : T; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment