Challenge - 5 Problems
Type Assertion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this TypeScript code with type assertion?
Consider the following TypeScript code using type assertion. What will be printed to the console?
Typescript
let someValue: unknown = "Hello TypeScript!"; let strLength: number = (someValue as string).length; console.log(strLength);
Attempts:
2 left
💡 Hint
Type assertion tells TypeScript to treat a value as a specific type.
✗ Incorrect
The variable someValue is asserted as a string, so accessing .length works and returns 17, the length of "Hello TypeScript!".
❓ Predict Output
intermediate2:00remaining
What error does this TypeScript code raise?
What error will this TypeScript code produce when compiled or run?
Typescript
let value: any = 123; let strLength: number = (value as string).length; console.log(strLength);
Attempts:
2 left
💡 Hint
Type assertion does not change the actual runtime type.
✗ Incorrect
At runtime, value is a number, so accessing .length causes a runtime error.
🧠 Conceptual
advanced2:00remaining
Which option correctly uses type assertion to access a property?
Given an object of unknown type, which option correctly asserts it as a specific type to access its property without error?
Attempts:
2 left
💡 Hint
Type assertion syntax uses 'as' followed by the type in parentheses.
✗ Incorrect
Option A correctly asserts obj as an object with a name property of type string, allowing access to .name.
📝 Syntax
advanced2:00remaining
Which option has correct syntax for type assertion in TypeScript?
Which of the following is the correct syntax for asserting a variable 'x' as type 'number'?
Attempts:
2 left
💡 Hint
Use 'as' keyword for type assertion in modern TypeScript.
✗ Incorrect
Option D uses the modern and recommended 'as' syntax for type assertion.
🚀 Application
expert3:00remaining
What is the value of 'result' after running this TypeScript code?
Analyze the code below and determine the value of 'result' after execution.
Typescript
interface User {
id: number;
name: string;
}
const data: unknown = {id: 42, name: "Bob"};
const user = data as User;
const result = user.id + user.name.length;Attempts:
2 left
💡 Hint
Type assertion does not change the actual runtime value.
✗ Incorrect
The object has id 42 and name "Bob" (length 3), so result is 42 + 3 = 45.