0
0
Typescriptprogramming~5 mins

Basic mapped type syntax 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 using a template. It lets you apply the same operation to all properties easily.
Click to reveal answer
beginner
Syntax of a basic mapped type
type NewType = { [Key in keyof OldType]: OldType[Key] }<br>This means: for each property Key in OldType, create a property Key with the same type.
Click to reveal answer
beginner
What does keyof do in mapped types?
keyof extracts all property names (keys) of a type as a union of string literal types. It helps to loop over all keys in a mapped type.
Click to reveal answer
intermediate
Example: Make all properties optional using mapped types
type Partial<T> = { [P in keyof T]?: T[P] }<br>This creates a new type where all properties of T are optional.
Click to reveal answer
intermediate
Can mapped types change property types?
Yes! You can transform property types. For example, { [P in keyof T]: string } makes all properties have type string regardless of original type.
Click to reveal answer
What does keyof return when used on a type?
AThe type's methods only
BThe type's values
CThe type's constructor
DA union of the type's property names
Which syntax correctly defines a mapped type over type T?
A{ [P in keyof T]: T[P] }
B{ T in keyof P: P[T] }
C{ [T of keyof P]: P[T] }
D{ [P of T]: keyof P }
How to make all properties of a type optional using mapped types?
A{ optional [P in keyof T]: T[P] }
B{ [P in keyof T]?: T[P] }
C{ [P in keyof T]: optional T[P] }
D{ [P in keyof T]: T[P]? }
Can mapped types change the type of properties?
AYes, they can assign new types to properties
BNo, they only copy original types
COnly for string properties
DOnly for number properties
What is the purpose of mapped types?
ATo define classes
BTo execute functions on objects
CTo create new types by transforming properties of existing types
DTo import modules
Explain how a basic mapped type works in TypeScript and give a simple example.
Think about looping over keys and creating a new type with the same properties.
You got /4 concepts.
    Describe how you can use mapped types to make all properties of a type optional.
    Focus on the question mark after the property name in the mapped type.
    You got /4 concepts.