0
0
Typescriptprogramming~5 mins

Mapped type with conditional types in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a mapped type in TypeScript?
A mapped type creates a new type by transforming each property of an existing type. It uses syntax like { [K in keyof T]: ... } to loop over keys.
Click to reveal answer
beginner
What does a conditional type do in TypeScript?
A conditional type chooses one type or another based on a condition, using syntax like T extends U ? X : Y. It works like an if-else for types.
Click to reveal answer
intermediate
How do mapped types and conditional types work together?
You can use conditional types inside mapped types to change each property type based on a condition. For example, making some properties optional or changing their type.
Click to reveal answer
intermediate
Example: What does this mapped type do?<br>
type ReadonlyIfString<T> = { [K in keyof T]: T[K] extends string ? Readonly : T[K] }
It makes properties readonly only if their type is string. Other properties keep their original type.
Click to reveal answer
beginner
Why use mapped types with conditional types?
They let you create flexible types that adapt property types based on conditions, making your code safer and easier to maintain.
Click to reveal answer
What does [K in keyof T] mean in a mapped type?
ADelete keys from T
BLoop over all keys of type T
CCreate a new key K unrelated to T
DAssign a fixed key K
In T extends U ? X : Y, what happens if T is assignable to U?
AType becomes X
BType becomes Y
CType becomes T
DType becomes U
Which is a valid use of conditional types inside a mapped type?
AAdding new properties
BChanging property names
CChanging property types based on their original type
DRemoving keys from the original type
What does this type do?<br>
type OptionalIfNumber<T> = { [K in keyof T]: T[K] extends number ? T[K] | undefined : T[K] }
AMakes number properties readonly
BMakes all properties optional
CRemoves number properties
DMakes number properties optional
Why are mapped types with conditional types useful?
AThey create flexible, type-safe transformations of object types
BThey speed up runtime code
CThey replace functions
DThey allow dynamic property names
Explain how mapped types and conditional types can be combined to change property types based on their original types.
Think about looping over keys and using if-else logic for types.
You got /3 concepts.
    Describe a real-life scenario where using a mapped type with conditional types would make your TypeScript code safer or easier to maintain.
    Consider objects with mixed property types needing different rules.
    You got /3 concepts.