Namespace-Style Key Transformations
What you'll learn: How to use as clauses in mapped types to create nested namespace structures or flatten deeply nested object keys.
Sometimes your data has flat keys like user_name and user_email, but you want them organized into a nested structure like user.name and user.email. Or the reverse: you have deeply nested keys and need to flatten them. Key remapping with as makes both transformations possible.
Building Namespace Structures from Flat Keys
Imagine you have configuration keys with prefixes:
type FlatConfig = {
db_host: string;
db_port: number;
cache_ttl: number;
cache_maxSize: number;
};
You can transform these into a namespace structure by splitting on the underscore:
type Namespaced<T> = {
[K in keyof T as K extends `${infer Prefix}_${string}`
? Prefix
: K]: {
[K2 in keyof T as K2 extends `${infer P}_${infer Suffix}`
? P extends K
? Suffix
: never
: never]: T[K2]
}
};
// Result: { db: { host: string; port: number }, cache: { ttl: number; maxSize: number } }
This pattern groups properties by their prefix into nested objects.
Flattening Nested Keys
The reverse is equally useful—turning user.name into user_name:
type Flatten<T> = {
[K in keyof T as `${K & string}_${keyof T[K] & string}`]: T[K][keyof T[K]]
};
This creates flat keys by concatenating the namespace with each property name.
Key Takeaway: Key remapping with as and template literals lets you restructure object shapes by grouping flat keys into namespaces or flattening nested structures—powerful for adapting between different data schemas.