0
0
Typescriptprogramming~20 mins

Optional properties in interfaces in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Optional Properties Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
ATypeError at runtime
B0
Cundefined
Dnull
Attempts:
2 left
💡 Hint
Optional properties may be missing and return undefined if not set.
Predict Output
intermediate
2: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);
A"A book"
Bundefined
Cnull
DCompilation error
Attempts:
2 left
💡 Hint
Optional means the property can be present or absent. Here it is present.
Predict Output
advanced
2: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 }));
A5000\n1000
Bundefined\n1000
C0\n1000
DCompilation error
Attempts:
2 left
💡 Hint
The nullish coalescing operator returns the right side if the left is null or undefined.
Predict Output
advanced
2: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);
Aundefined
Btrue
Cfalse
DTypeError
Attempts:
2 left
💡 Hint
The nullish coalescing operator assigns true if the property is undefined.
Predict Output
expert
2: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");
ARuntime error
Bundefined
Cnull
D"No street"
Attempts:
2 left
💡 Hint
Optional chaining safely accesses nested optional properties.