Challenge - 5 Problems
Explicit Type Annotations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of explicit type annotation with union type
What is the output of the following TypeScript code?
Typescript
function formatInput(input: string | number): string { if (typeof input === 'number') { return `Number: ${input.toFixed(2)}`; } else { return `String: ${input.toUpperCase()}`; } } console.log(formatInput(3.14159)); console.log(formatInput('hello'));
Attempts:
2 left
💡 Hint
Look at how the number is formatted with toFixed(2) and the string is converted to uppercase.
✗ Incorrect
The function checks if the input is a number or string. For numbers, it formats to 2 decimal places using toFixed(2). For strings, it converts to uppercase. So 3.14159 becomes '3.14' and 'hello' becomes 'HELLO'.
❓ Predict Output
intermediate1:30remaining
Value of variable with explicit tuple type
What is the value of the variable
data after running this code?Typescript
let data: [string, number]; data = ['age', 30]; console.log(data);
Attempts:
2 left
💡 Hint
Remember tuples have fixed order and types.
✗ Incorrect
The tuple
data expects a string first, then a number. The assigned value matches this order and types exactly.🔧 Debug
advanced1:30remaining
Identify the error caused by wrong explicit type annotation
What error will this TypeScript code produce?
Typescript
let count: string = 10; console.log(count);
Attempts:
2 left
💡 Hint
Check if the assigned value matches the declared type.
✗ Incorrect
The variable
count is declared as a string but assigned a number. TypeScript reports a type mismatch error.🧠 Conceptual
advanced1:00remaining
Effect of explicit type annotation on function parameters
Which statement about explicit type annotations on function parameters is true?
Attempts:
2 left
💡 Hint
Think about how TypeScript enforces types during compilation.
✗ Incorrect
Explicit type annotations on parameters restrict the types of arguments allowed. Passing a wrong type causes a compile-time error.
❓ Predict Output
expert2:00remaining
Output of explicit type annotation with intersection types
What is the output of this TypeScript code?
Typescript
type A = { x: number };
type B = { y: string };
const obj: A & B = { x: 5, y: 'hello' };
console.log(obj.x + obj.y.length);Attempts:
2 left
💡 Hint
Add the number x and the length of string y.
✗ Incorrect
The object has both properties x (number 5) and y (string 'hello'). y.length is 5, so 5 + 5 = 10.