Challenge - 5 Problems
Null Safety Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output with strict null checks enabled
What is the output of this TypeScript code when strict null checks are enabled?
Typescript
function greet(name: string | null) { if (name === null) { return "Hello, guest!"; } return `Hello, ${name.toUpperCase()}!`; } console.log(greet(null)); console.log(greet("alice"));
Attempts:
2 left
💡 Hint
Check how the function handles the null case before calling toUpperCase.
✗ Incorrect
The function checks if name is null and returns a special greeting. Otherwise, it safely calls toUpperCase on the string. This avoids runtime errors with null values.
❓ Predict Output
intermediate1:30remaining
Value of variable after null assertion
What is the value of variable 'length' after running this code with strict null checks enabled?
Typescript
let maybeString: string | null = "hello"; let length = maybeString!.length;
Attempts:
2 left
💡 Hint
The exclamation mark tells TypeScript the value is not null here.
✗ Incorrect
The null assertion operator (!) tells TypeScript to treat maybeString as non-null. Since it actually holds "hello", length is 5.
❓ Predict Output
advanced2:00remaining
Output of function with optional chaining and strict null checks
What is the output of this TypeScript code with strict null checks enabled?
Typescript
type User = { name: string; address?: { city: string } };
function getCity(user: User): string {
return user.address?.city ?? "Unknown city";
}
console.log(getCity({ name: "Bob", address: { city: "Paris" } }));
console.log(getCity({ name: "Alice" }));Attempts:
2 left
💡 Hint
Optional chaining safely accesses nested properties that might be missing.
✗ Incorrect
The optional chaining operator (?.) returns undefined if address is missing, so the nullish coalescing operator (??) returns "Unknown city" instead.
❓ Predict Output
advanced1:30remaining
Result of filtering null values with strict null checks
What is the output of this TypeScript code with strict null checks enabled?
Typescript
const values: (string | null)[] = ["a", null, "b", null, "c"]; const filtered = values.filter(v => v !== null); console.log(filtered);
Attempts:
2 left
💡 Hint
The filter removes all null values from the array.
✗ Incorrect
The filter callback keeps only elements not equal to null, so the resulting array contains only strings.
🧠 Conceptual
expert2:30remaining
Why does this code cause a compilation error with strict null checks?
Consider this TypeScript code with strict null checks enabled:
let input: string | null = null;
let length: number = input.length;
Why does this cause a compilation error?
Attempts:
2 left
💡 Hint
Think about what happens if input is null when accessing a property.
✗ Incorrect
With strict null checks, TypeScript prevents accessing properties on values that might be null to avoid runtime errors.