What is a mapped type?
- TypeScript course
- Intermediate
- Lesson 32/89
- 4 min
Learn mapped types that iterate over types.
What is a mapped type?
A mapped type iterates over all properties of a type and transforms each one. The syntax [K in keyof T] produces a property for each key K of T. The type expression on the right produces the new type by playing with the original value type T[K].
type Ayni<T> = {
[K in keyof T]: T[K];
};
// Every property of T is copied
// with the same typeThe power of mapped types
A mapped type takes a type and transforms each of its properties by the same rule. It can change the value type, add readonly, or make properties optional with ?. This is the foundation of built-in utility types like Partial and Readonly; you can write them yourself.
Practice Make all values string
Write the mapped type MetinYap<T> as { [K in keyof T]: string }. Define interface Ayar with tema: string and ses: number. Define type AyarMetin as MetinYap<Ayar>. Assign { tema: "koyu", ses: "acik" } to a variable a (of type AyarMetin). Print a.tema with console.log.
Starter code
// MetinYap<T> mapped type tanımla
// T'nin her özelliğini string değerli yap
// Ayar arayüzünü tema ve ses ile tanımla
// AyarMetin türünü MetinYap<Ayar> olarak tanımla
// a değişkenine uygun nesneyi ata
// tema değerini yazdırSample solution
type MetinYap<T> = {
[K in keyof T]: string;
};
interface Ayar {
tema: string;
ses: number;
}
type AyarMetin = MetinYap<Ayar>;
const a: AyarMetin = { tema: "koyu", ses: "acik" };
console.log(a.tema);Expected output
koyu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the mapped type below do?
type NumYap<T> = { [K in keyof T]: number };- Makes all of T's properties readonly
- Converts all of T's properties to number Correct answer
- Removes all of T's properties
- Makes all of T's properties optional
Explanation: Since the right-hand type is number, each property K gets a number value type. Property names come from T but the value type becomes number.
2 Mapped type body
type Dize<T> = {
[K in ____]: string;
};
type Dize<T> = {
[K in keyof T]: string;
};
Explanation: A mapped type must iterate over T's keys; that is why we write [K in keyof T]. Bare T is not a bound; string accepts any name; keyof K is the wrong direction.
3 Mapped type parts
| Term | Meaning |
|---|---|
[K in keyof T] |
Iterates over T's properties |
T[K] |
Original property's value type |
: string |
New value type |
type NumYap<T> |
Mapped type alias |