0
0
Typescriptprogramming~5 mins

Mapped type modifiers (readonly, optional) in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the readonly modifier do in a mapped type?
It makes all properties in the mapped type read-only, meaning their values cannot be changed after initialization.
Click to reveal answer
beginner
How do you make all properties optional in a mapped type?
By adding the ? modifier after the property name in the mapped type, like [P in keyof T]?: T[P].
Click to reveal answer
intermediate
What is the effect of using +readonly and -readonly in mapped types?
+readonly adds the readonly modifier to properties, while -readonly removes it if it was present.
Click to reveal answer
intermediate
Explain the difference between +? and -? in mapped types.
+? makes properties optional, -? makes them required (removes optional).
Click to reveal answer
beginner
Show a simple example of a mapped type that makes all properties readonly and optional.
type ReadonlyOptional<T> = { readonly [P in keyof T]?: T[P] };
Click to reveal answer
What does { readonly [P in keyof T]: T[P] } do?
AMakes all properties writable
BMakes all properties of T optional
CMakes all properties of T readonly
DRemoves readonly from all properties
How do you remove the optional modifier from all properties in a mapped type?
A[P in keyof T]?: T[P]
B[P in keyof T]+readonly T[P]
C[P in keyof T]+?: T[P]
D[P in keyof T]-?: T[P]
What does { -readonly [P in keyof T]: T[P] } do?
ARemoves readonly from all properties
BMakes all properties optional
CAdds readonly to all properties
DMakes all properties required
Which syntax makes all properties optional in a mapped type?
A[P in keyof T]+?: T[P]
B[P in keyof T]?: T[P]
C[P in keyof T]-?: T[P]
D[P in keyof T]+readonly T[P]
What is the result of { readonly [P in keyof T]?: T[P] }?
AAll properties are optional and readonly
BAll properties are optional and writable
CAll properties are required and readonly
DAll properties are required and writable
Explain how to use mapped type modifiers to make all properties readonly and optional in TypeScript.
Think about adding +readonly and ? in the mapped type.
You got /4 concepts.
    Describe the difference between + and - modifiers in mapped types for readonly and optional properties.
    Consider how you can add or remove modifiers explicitly.
    You got /5 concepts.