ts-simple-mapper
Version:
A lightweight utility for mapping object properties between different shapes
47 lines (44 loc) • 1.5 kB
TypeScript
/**
* Type representing an object with string keys and any values
*/
type AnyObject = Record<string, any>;
/**
* Configuration options for the simpleMap function
*/
type MapOptions<T = any> = {
exclude?: string[];
transforms?: {
[K in keyof T]?: Transform<T[K]>;
};
fieldMappings?: Record<string, string>;
deep?: boolean;
};
type Transform<T> = ((value: T) => any) | (T extends object ? {
[K in keyof T]?: Transform<T[K]>;
} : never);
/**
* Maps properties from a source object to a target object with support for
* field exclusions, custom transformations, and field name mappings.
*
* @param source The source object to map from
* @param options Configuration options for the mapping
* @param options.exclude Array of field names to exclude from mapping
* @param options.transforms Object containing custom transformation functions for specific fields
* @param options.fieldMappings Object mapping source field names to target field names
* @returns A new object with the mapped fields
*
* @example
* const result = simpleMap<Source, Target>(sourceObject, {
* exclude: ['internalId'],
* transforms: {
* date: (value) => new Date(value),
* amount: (value) => parseFloat(value)
* },
* fieldMappings: {
* full_name: 'name',
* user_id: 'id'
* }
* });
*/
declare function simpleMap<T extends AnyObject, R>(source: T, options?: MapOptions): R;
export { type AnyObject, type MapOptions, type Transform, simpleMap };