0
0
Typescriptprogramming~5 mins

Optional properties in interfaces in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean when a property in a TypeScript interface is marked with a question mark (e.g., age?: number)?
It means the property is optional. Objects implementing the interface may or may not include that property.
Click to reveal answer
beginner
How do you declare an optional property named email of type string in a TypeScript interface?
You write email?: string; inside the interface definition.
Click to reveal answer
beginner
Can an object that implements an interface with optional properties omit those properties?
Yes, optional properties can be left out when creating an object that implements the interface.
Click to reveal answer
intermediate
What happens if you try to access an optional property that is not provided in an object?
The property will be undefined. You should check if it exists before using it.
Click to reveal answer
intermediate
Why are optional properties useful in TypeScript interfaces?
They allow flexibility by letting objects have some properties but not requiring all, making interfaces adaptable to different situations.
Click to reveal answer
How do you mark a property as optional in a TypeScript interface?
AAdd an exclamation mark (!) after the property name
BUse the keyword 'optional' before the property name
CAdd a question mark (?) after the property name
DUse the keyword 'nullable' before the property name
If an interface has an optional property, can an object omit that property when implementing the interface?
AYes, it can omit the optional property
BNo, all properties must be present
COnly if the property is a string
DOnly if the property is a number
What is the type of an optional property if it is not provided in an object?
Anull
Bundefined
Cempty string
Dzero
Which of the following is a correct optional property declaration in an interface?
Aphone?: string;
Bphone!: string;
Coptional phone: string;
Dphone: string?;
Why might you use optional properties in an interface?
ATo make properties private
BTo force all objects to have the same properties
CTo make properties readonly
DTo allow objects to have flexible sets of properties
Explain what optional properties in TypeScript interfaces are and how they affect object creation.
Think about how you can leave some details out when describing something.
You got /4 concepts.
    Describe a real-life example where optional properties in an interface would be useful.
    Consider a form where some fields are not required.
    You got /3 concepts.