0
0
Typescriptprogramming~20 mins

Type assertions in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Assertion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
ACompilation error
Bundefined
C17
DTypeError at runtime
Attempts:
2 left
💡 Hint
Type assertion tells TypeScript to treat a value as a specific type.
Predict Output
intermediate
2: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);
ARuntime error: Cannot read property 'length' of number
BOutputs undefined
CCompilation error: Cannot assert number to string
DOutputs 3
Attempts:
2 left
💡 Hint
Type assertion does not change the actual runtime type.
🧠 Conceptual
advanced
2: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?
A
let obj: unknown = {name: "Alice"};
console.log((obj as {name: string}).name);
B
let obj: unknown = {name: "Alice"};
console.log(obj.name);
C
let obj: unknown = {name: "Alice"};
console.log(<{name: string}>obj.name);
D
let obj: unknown = {name: "Alice"};
console.log(obj as name);
Attempts:
2 left
💡 Hint
Type assertion syntax uses 'as' followed by the type in parentheses.
📝 Syntax
advanced
2: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'?
Alet y = x <number>;
Blet y = x : number;
Clet y = <number> x;
Dlet y = x as number;
Attempts:
2 left
💡 Hint
Use 'as' keyword for type assertion in modern TypeScript.
🚀 Application
expert
3: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;
ACompilation error
B45
CTypeError at runtime
DNaN
Attempts:
2 left
💡 Hint
Type assertion does not change the actual runtime value.