0
0
Typescriptprogramming~20 mins

Optional properties 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 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);
Anull
B0
Cundefined
DTypeError
Attempts:
2 left
💡 Hint
Optional properties may not exist on the object.
Predict Output
intermediate
2: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");
}
A0
BNo description
Cundefined
DTypeError
Attempts:
2 left
💡 Hint
Check if optional property exists before accessing.
🔧 Debug
advanced
2: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({});
ASyntax error in interface declaration
B'timeout' is missing and cannot be accessed
CFunction setTimeoutValue requires timeout property to be present
DProperty 'timeout' might be undefined, so adding number causes error
Attempts:
2 left
💡 Hint
Optional properties can be undefined and need checks before use.
📝 Syntax
advanced
2:00remaining
Which option correctly defines an optional property?
Which of these interface property declarations correctly defines an optional property named 'email' of type string?
Aemail?: string;
Bemail: string?;
Cemail: string | undefined;
Doptional email: string;
Attempts:
2 left
💡 Hint
Optional properties use a special syntax with a question mark after the name.
🚀 Application
expert
3: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);
A3
B1
C0
D2
Attempts:
2 left
💡 Hint
Optional properties can be added later by assignment.