Challenge 3: Type systems
- TypeScript course
- Intermediate
- Lesson 88/89
- 6 min
Solve a task combining mapped, conditional, and infer.
Type systems challenge
In this challenge you will solve tasks that combine mapped types, conditional types, and the infer keyword. You learned to transform all fields of a type with mapped types, build type-based logic with conditional types, and extract one type from another with infer.
Practice ReadOnly mapped type
Define a mapped type named ReadOnly: { readonly [K in keyof T]: T[K] }. The Nokta interface should contain x: number and y: number. The p variable should be of type ReadOnly<Nokta> with value { x: 3, y: 4 }. Print p.x + p.y with console.log.
Starter code
// ReadOnly adinda mapped type tanimla
// Nokta adinda interface tanimla
// p nesnesi readonly Nokta olsun
// p.x + p.y yazdirSample solution
type ReadOnly<T> = { readonly [K in keyof T]: T[K] };
interface Nokta { x: number; y: number; }
const p: ReadOnly<Nokta> = { x: 3, y: 4 };
console.log(p.x + p.y);Expected output
7
Practice Element type with infer
Define a conditional type named Eleman: T extends (infer U)[] ? U : never. Define R as Eleman<string[]>. The deger variable should be of type R with value "merhaba". Print deger with console.log.
Starter code
// Eleman adinda conditional type tanimla
// dizi türünden eleman türünü cikar
// degilse bos tür olsun
// R türü string dizisi elemani olsun
// deger: R = "merhaba"
// deger yazdirSample solution
type Eleman<T> = T extends (infer U)[] ? U : never;
type R = Eleman<string[]>;
const deger: R = "merhaba";
console.log(deger);Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword is used to extract the value type from a Promise in a conditional type?
- typeof
- keyof
- infer Correct answer
- extends
Explanation: The infer keyword performs type inference inside a conditional type; for example T extends Promise<infer U> ? U : never.
2 Type extraction with infer
type Eleman<T> = T extends (____ U)[] ? U : never;
type Eleman<T> = T extends (infer U)[] ? U : never;
Explanation: The infer keyword declares a type variable inside a conditional type and assigns the extracted type to it.
3 Type system concepts
| Term | Meaning |
|---|---|
mapped |
[K in keyof T] |
conditional |
T extends U ? X : Y |
infer |
Type extraction |
keyof |
Key set |