Generation with mapped
- TypeScript course
- Advanced
- Lesson 7/57
- 4 min
Learn to generate string types with mapped types.
What is mapped generation?
With a mapped type you can iterate over a union and produce a template literal value for each member. In the form [K in Union]: `data_${K}`, each key is bound to a string type containing its own name. This is a powerful way to produce type-safe dictionary types.
type Key = "name" | "age";
type Value = {
[K in Key]: `data_${K}`;
};
// { name: "data_name"; age: "data_age" }Key generation with remapping
In a mapped type, you can rename keys with the as keyword. In the form [K in Kaynak as `get_${K}`], a new template literal key is generated from each source key. This is ideal for producing getter/setter names.
type Source = "name" | "age";
type Get = {
[K in Source as `get_${K}`]: string;
};
// { get_name: string; get_age: string }Practice Mapped type generating getters
Define a union named Kaynak: "ad" | "yas". Define a mapped type named Getir: for each K in Kaynak use [K in Kaynak as `get_${K}`]: string. The g variable should be of type Getir with value { get_ad: "Ali", get_yas: "30" }. Print g.get_ad with console.log.
Starter code
// Kaynak adinda union tanimla
// Getir mapped type ile get_ onekli anahtarlar uret
// her anahtar string deger tursun
// g nesnesini tanimla
// g.get_ad yazdirSample solution
type Kaynak = "ad" | "yas";
type Getir = {
[K in Kaynak as `get_${K}`]: string;
};
const g: Getir = { get_ad: "Ali", get_yas: "30" };
console.log(g.get_ad);Expected output
Ali
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the mapped type [K in Anahtar]: `veri_${K}` produce?
- A single combined string
- A template literal value for each key Correct answer
- An empty object type
- A number array
Explanation: The mapped type produces a separate template literal value for each key; the result is an object type binding each key to its own string value.
2 Key remapping variable
type Kaynak = "ad" | "yas";
type Getir = {
[K in Kaynak as `get_${____}`]: string;
};
type Kaynak = "ad" | "yas";
type Getir = {
[K in Kaynak as `get_${K}`]: string;
};
Explanation: In a mapped type, K is the loop variable; during key remapping, K is placed inside the template literal.
3 Mapped generation concepts
| Term | Meaning |
|---|---|
[K in Union] |
Mapped loop |
as |
Key renaming |
`get_${K}` |
Template key |
K |
Loop variable |