Preserving Property Types
What you'll learn: How to use T[K] to keep each property's original type intact when transforming object shapes with mapped types.
The Problem: Losing Type Information
When you create a mapped type, you're essentially building a new object type by looping over the keys of another type. Without the right technique, you might accidentally give all properties the same type (like string or boolean), losing the specific types each property originally had.
The Solution: Lookup Types with T[K]
The syntax T[K] is a lookup type — it means "give me the type of property K from type T." When used inside a mapped type, it preserves the original type of each property as you transform it.
Basic Pattern
type Original = {
name: string;
age: number;
active: boolean;
};
// Without preservation - everything becomes string (wrong!)
type WrongWrap<T> = {
[K in keyof T]: string;
};
// With T[K] - each property keeps its original type
type Wrap<T> = {
[K in keyof T]: { value: T[K] };
};
type WrappedOriginal = Wrap<Original>;
// Result:
// {
// name: { value: string };
// age: { value: number };
// active: { value: boolean };
// }
Notice how T[K] accesses the original type of each property, so name stays string, age stays number, and active stays boolean.
Think of It Like...
Imagine you're wrapping presents of different shapes. T[K] is like looking at each item before wrapping it to use the right-sized box — it remembers what's inside.
Key Takeaway: Use T[K] in mapped types to preserve the original type of each property you're transforming, maintaining type safety throughout your type transformations.