0
0
Typescriptprogramming~20 mins

Type annotation on variables in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Annotation 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 variable type annotations?
Consider the following TypeScript code snippet. What will be logged to the console?
Typescript
let count: number = 5;
let message: string = "Hello";
count = count + 10;
console.log(message + " " + count);
A"Hello 15"
B"Hello 5"
CTypeError at runtime
DCompilation error due to type mismatch
Attempts:
2 left
💡 Hint
Look at how the variables are typed and how their values change before logging.
Predict Output
intermediate
2:00remaining
What error occurs when assigning wrong type to a typed variable?
What happens when you run this TypeScript code?
Typescript
let isActive: boolean = true;
isActive = "yes";
ANo error, isActive becomes 'yes'
BRuntime error: Cannot assign string to boolean.
COutput: true
DCompilation error: Type 'string' is not assignable to type 'boolean'.
Attempts:
2 left
💡 Hint
Check the type of the variable and the assigned value.
🔧 Debug
advanced
2:00remaining
Why does this TypeScript code cause a compilation error?
Identify the cause of the error in this code snippet.
Typescript
let data: number;
data = 10;
data = "twenty";
AError because 'data' is not initialized at declaration.
BError because 'data' is declared as number but assigned a string.
CNo error, TypeScript allows changing types.
DError because 'data' is declared with let instead of const.
Attempts:
2 left
💡 Hint
Look at the type annotation and the assigned values.
🧠 Conceptual
advanced
2:00remaining
What is the purpose of type annotation on variables in TypeScript?
Choose the best explanation for why we use type annotations on variables.
ATo allow variables to change types dynamically during runtime.
BTo make the code run faster by specifying types explicitly.
CTo tell the compiler what type a variable should hold, enabling type checking and preventing errors.
DTo automatically convert variables to strings when needed.
Attempts:
2 left
💡 Hint
Think about how TypeScript helps catch mistakes before running the code.
Predict Output
expert
2:00remaining
What is the output of this TypeScript code with union type annotation?
Analyze the following code and select the correct console output.
Typescript
let value: number | string;
value = 42;
console.log(typeof value);
value = "forty-two";
console.log(typeof value);
A"number" followed by "string"
BCompilation error due to union type usage
C"string" followed by "number"
D"number" twice
Attempts:
2 left
💡 Hint
Check the type of 'value' after each assignment.