Created
October 18, 2023 16:44
-
-
Save nikolaskhodov/547a112a134556fe5848e85791c6ae4f to your computer and use it in GitHub Desktop.
Transform generic objects with type guargs only
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
| import { keys } from 'ts-transformer-keys'; | |
| export type ConvertibleToNumber<T> = { | |
| [K in keyof T]: number | string; | |
| }; | |
| function isNumeric(value: string): boolean { | |
| return isFinite(parseFloat(value)); | |
| } | |
| function isComplete<T>(obj: any): obj is T { | |
| const prototypeKeys = keys<T>(); | |
| for (const key of prototypeKeys) { | |
| if (obj[key] === undefined) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| function convertStrings<T extends Record<string, string>>( | |
| input: T | |
| ): ConvertibleToNumber<T> { | |
| const output: Partial<ConvertibleToNumber<T>> = {}; | |
| for (const key in input) { | |
| const value = input[key]; | |
| if (!value) { | |
| continue; | |
| } | |
| if (isNumeric(value)) { | |
| output[key] = parseFloat(value); | |
| } else { | |
| output[key] = value; | |
| } | |
| } | |
| if (!isComplete<ConvertibleToNumber<T>>(output)) { | |
| throw new Error('Something went wrong'); | |
| } | |
| return output; | |
| } | |
| const data = { | |
| name: 'John', | |
| age: '25', | |
| }; | |
| const convertedData = convertStrings(data); | |
| console.log(convertedData); // { name: 'John', age: 25 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment