Zero-duplication field mapping for TypeScript with full type safety and inference.
Transform data between different shapes (API ↔ Domain) without writing repetitive boilerplate. Define your field mappings once, and let TypeScript infer the types automatically.
- Why?
- Quick Start
- Key Features
- Validation
- Advanced Features
- API Reference
- Key Introspection
- Constructor Injection (Factory Pattern)
- Use Cases
- Important Notes
- Contributing
- License
When mapping between API responses and domain models, you typically need to:
- Define field mappings
- Manually write the transformation logic
- Manually define the resulting type
This leads to duplication and maintenance burden. This package eliminates that by using TypeScript's type system to infer the mapped type from your field mapping definition.
npm install @kylebrodeur/type-safe-mapping
# or
yarn add @kylebrodeur/type-safe-mapping
# or
pnpm add @kylebrodeur/type-safe-mappingkylebrodeur
import { MappedServiceBase, MappedType } from '@kylebrodeur/type-safe-mapping';
// 1. Define your source type (e.g., API response)
interface ApiRow {
custom_a: boolean;
custom_b: string;
optional_c?: number;
[key: string]: unknown;
}
// 2. Define your field mapping with 'as const'
const fieldMapping = {
custom_a: 'isEnterprise',
custom_b: 'commerceType',
} as const;
// 3. (Optional) Infer the domain type
type Domain = MappedType<ApiRow, typeof fieldMapping>;
// Result: { isEnterprise: boolean; commerceType: string; }
// 4. Create your mapper service
class UserMapper extends MappedServiceBase<ApiRow, typeof fieldMapping> {
protected fieldMapping = fieldMapping;
}
// 5. Use it!
const mapper = new UserMapper();
// Map external → internal
const domain = mapper.map({ custom_a: true, custom_b: 'B2B' });
// { isEnterprise: true, commerceType: 'B2B' }
// Map internal → external
const api = mapper.reverseMap({ isEnterprise: false, commerceType: 'B2C' });
// { custom_a: false, custom_b: 'B2C' }- Zero Duplication: Define field mappings once, get TypeScript types automatically
- Full Type Safety: TypeScript infers mapped types from your field mappings
- Bidirectional: Map from external → internal and internal → external
- Deep Path Support: Use dot notation for nested field mappings (e.g.,
'user.profile.name') - Optional Fields: Handles optional values correctly in both directions
- Pass-Through Mode: Preserve unmapped fields with
allowPassThroughoption - Zero Dependencies: No runtime dependencies
- Built-in Validation: Lightweight runtime validation with no extra dependencies
Pass { validate: true } as a second argument to map() or reverseMap() to enable runtime
validation. Validation is disabled by default to maintain full backward compatibility.
When validate: true, all fields defined in your mapping must be present in the source object.
const mapper = new UserMapper();
// ✅ Passes — all mapped fields are present
mapper.map({ custom_a: true, custom_b: 'B2B' }, { validate: true });
// ❌ Throws: "Validation failed:\nMissing required field `custom_b` in source."
mapper.map({ custom_a: true }, { validate: true });By default, extra (unmapped) fields in the source are silently ignored. Set
allowUnknownFields: false to throw instead.
// ✅ Extra fields allowed by default
mapper.map({ custom_a: true, custom_b: 'B2B', extra: 'ignored' }, { validate: true });
// ❌ Throws: "Validation failed:\nUnmapped field `extra` is not allowed."
mapper.map(
{ custom_a: true, custom_b: 'B2B', extra: 'unexpected' },
{ validate: true, allowUnknownFields: false },
);Use validateWith to integrate any validation library (e.g. Zod, Yup) or your own logic.
validateWith runs whenever it is provided, regardless of the validate flag.
import { z } from 'zod';
const schema = z.object({ custom_a: z.boolean(), custom_b: z.string() });
// Runs the Zod schema parse as part of the mapping call
mapper.map(data, {
validateWith: (source) => schema.parse(source),
});Throw an error inside validateWith to signal a validation failure:
mapper.map(data, {
validateWith: (source) => {
if (typeof (source as ApiRow).custom_a !== 'boolean') {
throw new Error('custom_a must be a boolean');
}
},
});| Option | Type | Default | Description |
|---|---|---|---|
validate |
boolean |
false |
Enable built-in field-presence and unknown-field checks |
allowUnknownFields |
boolean |
true |
Allow unmapped source fields when validate: true |
validateWith |
(data: unknown) => void |
— | Custom validator; runs whenever provided |
allowPassThrough |
boolean |
false |
Preserve unmapped fields in output (see Advanced Features) |
stripUndefined |
boolean |
true |
Exclude undefined values from mapping (see Advanced Features) |
Use dot notation in your field mappings to access nested properties:
interface ApiResponse {
user: {
profile: {
firstName: string;
lastName: string;
};
};
metadata: {
created: number;
};
[key: string]: unknown;
}
const mapping = {
'user.profile.firstName': 'firstName',
'user.profile.lastName': 'lastName',
'metadata.created': 'createdAt',
} as const;
class NestedMapper extends MappedServiceBase<ApiResponse, typeof mapping> {
protected fieldMapping = mapping;
}
const mapper = new NestedMapper();
const result = mapper.map({
user: { profile: { firstName: 'Jane', lastName: 'Smith' } },
metadata: { created: 1714435200 },
});
// { firstName: 'Jane', lastName: 'Smith', createdAt: 1714435200 }By default, only mapped fields are included in the output. Set allowPassThrough: true to preserve all unmapped fields:
const result = mapper.map(
{ custom_a: true, custom_b: 'B2B', extraField: 'preserved' },
{ allowPassThrough: true },
);
// { isEnterprise: true, commerceType: 'B2B', extraField: 'preserved' }This is useful when:
- You want to preserve metadata or timestamps from API responses
- You need to pass through fields that don't require transformation
- You're working with dynamic data structures
By default, undefined values are excluded from the output (stripUndefined: true). To explicitly map undefined values:
const result = mapper.map(
{ custom_a: undefined, custom_b: 'B2B' },
{ stripUndefined: false },
);
// { isEnterprise: undefined, commerceType: 'B2B' }This allows you to intentionally clear fields or work with APIs that distinguish between absent and undefined values.
Abstract base class for creating type-safe field mappers.
Type Parameters:
TSource: The source object type (e.g., API response)TMapping: The field mapping definition (usetypeof yourMapping)
Methods:
map(source: Partial<TSource>, options?: MapOptions): MappedType<TSource, TMapping>- Transform external to internalreverseMap(target: Partial<MappedType<TSource, TMapping>>, options?: MapOptions): Partial<TSource>- Transform internal to externalgetAllKeys(): { external: string[]; internal: string[] }- Get arrays of all external and internal field namesgetKeySet(): Set<string>- Get a Set containing all field names (external and internal combined)
Options object accepted by map() and reverseMap().
interface MapOptions {
validate?: boolean; // Enable built-in validation (default: false)
allowUnknownFields?: boolean; // Allow unmapped fields when validate: true (default: true)
validateWith?: (data: unknown) => void; // Custom validator hook
allowPassThrough?: boolean; // Preserve unmapped fields in output (default: false)
stripUndefined?: boolean; // Exclude undefined values from mapping (default: true)
}A concrete implementation of MappedServiceBase that accepts field mapping via constructor.
import { FieldMapper } from '@kylebrodeur/type-safe-mapping';
const mapping = { external_field: 'internalField' } as const;
const mapper = new FieldMapper(mapping);Type Parameters:
TSource: The source object typeTMapping: The field mapping definition (usetypeof yourMapping)
Constructor:
new FieldMapper(fieldMapping: TMapping)
All methods from MappedServiceBase are available (map, reverseMap, getAllKeys, getKeySet).
Factory function that creates a FieldMapper instance.
import { createMapper } from '@kylebrodeur/type-safe-mapping';
const mapper = createMapper({ api_id: 'id', api_name: 'name' } as const);
const result = mapper.map({ api_id: '123', api_name: 'Test' });Parameters:
fieldMapping: The field mapping definition withas constassertion
Returns: A FieldMapper instance
Standalone validation utility used internally by MappedServiceBase. Can also be called
directly when you need finer control.
import { validateMapping } from '@kylebrodeur/type-safe-mapping';
validateMapping(
{ custom_a: true, custom_b: 'B2B' }, // source object
['custom_a', 'custom_b'], // expected keys
{ allowUnknownFields: false }, // options
);Type utility that infers the resulting domain type from a source type and field mapping.
Type constraint for valid field mappings: Record<TExternal, keyof TSource>
Internal type utility for reverse lookup in field mappings.
Sometimes you need to enumerate all fields involved in a mapping (both external and internal) for operations like purging, filtering, or excluding mapped fields from other operations.
Returns an object with separate arrays for external and internal field names:
const mapper = new UserMapper();
const keys = mapper.getAllKeys();
// {
// external: ['custom_a', 'custom_b'],
// internal: ['isEnterprise', 'commerceType']
// }Use cases:
- Generating documentation or field lists
- Creating exclusion/inclusion filters
- Debugging which fields are in the mapping
Returns a Set<string> containing all keys from both directions:
const mapper = new UserMapper();
const allKeys = mapper.getKeySet();
// Set(4) { 'custom_a', 'custom_b', 'isEnterprise', 'commerceType' }Use cases:
- Filtering out all mapped fields from an object
- Checking if a field name is part of the mapping (in either direction)
- Purging mapped data before saving to avoid duplication
Example: Purge mapped fields
const allMappedKeys = mapper.getKeySet();
const data = { custom_a: true, isEnterprise: false, unrelated: 'keep' };
const filtered = Object.fromEntries(
Object.entries(data).filter(([key]) => !allMappedKeys.has(key))
);
// { unrelated: 'keep' }The traditional pattern requires creating a subclass and defining protected fieldMapping:
class UserMapper extends MappedServiceBase<ApiRow, typeof fieldMapping> {
protected fieldMapping = fieldMapping;
}For simpler use cases, you can use FieldMapper or createMapper() for inline mapper creation without subclassing:
A concrete mapper implementation that accepts the field mapping in its constructor:
import { FieldMapper } from '@kylebrodeur/type-safe-mapping';
const mapping = { custom_a: 'isEnterprise', custom_b: 'commerceType' } as const;
const mapper = new FieldMapper(mapping);
const result = mapper.map({ custom_a: true, custom_b: 'B2B' });
// { isEnterprise: true, commerceType: 'B2B' }A factory function that creates a FieldMapper instance. Convenient for inline usage:
import { createMapper } from '@kylebrodeur/type-safe-mapping';
const mapper = createMapper({ api_id: 'id', api_name: 'name' } as const);
const user = mapper.map({ api_id: '123', api_name: 'John' });
// { id: '123', name: 'John' }✅ Use FieldMapper / createMapper() when:
- You need a quick mapper for a one-off transformation
- Your mapping logic is simple and doesn't need extra methods
- You want to avoid creating a class hierarchy
❌ Use the subclass pattern when:
- You need to add custom transformation methods or business logic
- You want to encapsulate mapper behavior in a class with methods
- Your mapper is a core part of your domain layer
Both approaches support all mapper methods (map, reverseMap, getAllKeys, getKeySet) and validation options.
// Transform snake_case API responses to camelCase domain models
interface ApiUser {
user_id: string;
first_name: string;
last_name: string;
email_address: string;
[key: string]: unknown;
}
const userMapping = {
user_id: 'id',
first_name: 'firstName',
last_name: 'lastName',
email_address: 'email',
} as const;
class UserMapper extends MappedServiceBase<ApiUser, typeof userMapping> {
protected fieldMapping = userMapping;
}
const mapper = new UserMapper();
const user = mapper.map({
user_id: '123',
first_name: 'John',
last_name: 'Doe',
email_address: 'john@example.com',
});
// Result: { id: '123', firstName: 'John', lastName: 'Doe', email: 'john@example.com' }// Map database columns to domain models
interface DbProduct {
product_sku: string;
product_name: string;
unit_price: number;
is_active: boolean;
[key: string]: unknown;
}
const productMapping = {
product_sku: 'sku',
product_name: 'name',
unit_price: 'price',
is_active: 'active',
} as const;
type Product = MappedType<DbProduct, typeof productMapping>;
// Result: { sku: string; name: string; price: number; active: boolean; }// Normalize data from external services
interface StripeCustomer {
id: string;
email: string;
created: number;
default_source: string;
[key: string]: unknown;
}
const stripeMapping = {
id: 'customerId',
email: 'customerEmail',
created: 'createdAt',
default_source: 'paymentMethodId',
} as const;- Always use
as conston your field mapping definitions to preserve literal types - Source types must include an index signature
[key: string]: unknownto satisfy TypeScript's constraintsinterface ApiResponse { field_one: string; field_two: number; [key: string]: unknown; // ← Required }
- Only mapped fields are included in the result (unmapped fields are ignored)
- Optional fields in the source type are handled correctly
- The mapper extends
MappedServiceBaseand must defineprotected fieldMapping
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
MIT © Kyle Brodeur