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 properties
What is the output of this TypeScript code when compiled and run with Node.js?
Typescript
interface User {
name: string;
age?: number;
}
const user1: User = { name: "Alice" };
console.log(user1.age);Attempts:
2 left
💡 Hint
Optional properties may be missing and return undefined if not set.
✗ Incorrect
The property age is optional, so it may not exist on the object. Accessing it returns undefined rather than an error or default value.
❓ Predict Output
intermediate2:00remaining
Output when optional property is assigned
What will be printed by this TypeScript code?
Typescript
interface Product {
id: number;
description?: string;
}
const p: Product = { id: 101, description: "A book" };
console.log(p.description);Attempts:
2 left
💡 Hint
Optional means the property can be present or absent. Here it is present.
✗ Incorrect
The description property is optional but is provided in the object. So, logging it prints the string value.
❓ Predict Output
advanced2:00remaining
Output of function using optional property
What is the output of this TypeScript code?
Typescript
interface Config {
timeout?: number;
}
function getTimeout(config: Config): number {
return config.timeout ?? 5000;
}
console.log(getTimeout({}));
console.log(getTimeout({ timeout: 1000 }));Attempts:
2 left
💡 Hint
The nullish coalescing operator returns the right side if the left is null or undefined.
✗ Incorrect
The timeout property is optional. If missing, the function returns 5000 as default. If present, it returns the given value.
❓ Predict Output
advanced2:00remaining
Result of assigning object missing optional property
What will be the value of
obj after this code runs?Typescript
interface Settings {
darkMode?: boolean;
}
const obj: Settings = {};
obj.darkMode = obj.darkMode ?? true;
console.log(obj.darkMode);Attempts:
2 left
💡 Hint
The nullish coalescing operator assigns true if the property is undefined.
✗ Incorrect
Since darkMode is missing (undefined), the expression assigns true to it.
❓ Predict Output
expert2:00remaining
Output of nested optional properties access
What is the output of this TypeScript code?
Typescript
interface Address {
street?: string;
}
interface Person {
name: string;
address?: Address;
}
const person: Person = { name: "Bob" };
console.log(person.address?.street ?? "No street");Attempts:
2 left
💡 Hint
Optional chaining safely accesses nested optional properties.
✗ Incorrect
The address property is missing, so person.address?.street is undefined. The nullish coalescing operator then returns "No street".