Challenge - 5 Problems
Optional Properties Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing optional property
What is the output of this TypeScript code?
Typescript
interface User {
name: string;
age?: number;
}
const user: User = { name: "Alice" };
console.log(user.age);Attempts:
2 left
💡 Hint
Optional properties may not exist on the object.
✗ Incorrect
The property 'age' is optional and not set, so accessing it returns undefined.
❓ Predict Output
intermediate2:00remaining
Output when optional property is checked
What will this code output?
Typescript
interface Product {
id: number;
description?: string;
}
const product: Product = { id: 101 };
if (product.description) {
console.log(product.description.length);
} else {
console.log("No description");
}Attempts:
2 left
💡 Hint
Check if optional property exists before accessing.
✗ Incorrect
Since 'description' is undefined, the else branch runs printing 'No description'.
🔧 Debug
advanced2:00remaining
Why does this code cause an error?
This TypeScript code causes a compilation error. What is the reason?
Typescript
interface Config {
timeout?: number;
}
function setTimeoutValue(config: Config) {
const time = config.timeout + 1000;
console.log(time);
}
setTimeoutValue({});Attempts:
2 left
💡 Hint
Optional properties can be undefined and need checks before use.
✗ Incorrect
Since 'timeout' can be undefined, adding 1000 to it without checking causes a type error.
📝 Syntax
advanced2:00remaining
Which option correctly defines an optional property?
Which of these interface property declarations correctly defines an optional property named 'email' of type string?
Attempts:
2 left
💡 Hint
Optional properties use a special syntax with a question mark after the name.
✗ Incorrect
The correct syntax for optional properties is placing '?' after the property name before the colon.
🚀 Application
expert3:00remaining
How many keys are in the resulting object?
Given this code, how many keys does the object 'settings' have after execution?
Typescript
interface Settings {
theme?: string;
fontSize?: number;
language?: string;
}
const settings: Settings = { theme: "dark" };
if (settings.fontSize === undefined) {
settings.fontSize = 14;
}
if (!settings.language) {
settings.language = "en";
}
console.log(Object.keys(settings).length);Attempts:
2 left
💡 Hint
Optional properties can be added later by assignment.
✗ Incorrect
Initially only 'theme' is set. Then 'fontSize' and 'language' are assigned, so total keys are 3.