Challenge - 5 Problems
Array Type Annotation 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 array type annotation?
Consider the following TypeScript code snippet. What will be logged to the console?
Typescript
function sumNumbers(numbers: number[]): number { return numbers.reduce((acc, val) => acc + val, 0); } console.log(sumNumbers([1, 2, 3, 4]));
Attempts:
2 left
💡 Hint
Look at how the array is typed and how reduce sums the values.
✗ Incorrect
The function sumNumbers takes an array of numbers and returns their sum using reduce. The input array [1, 2, 3, 4] sums to 10, so the output is 10.
❓ Predict Output
intermediate2:00remaining
What error does this TypeScript code raise?
What error will this TypeScript code produce when compiled?
Typescript
let names: string[] = ["Alice", "Bob", 42];
Attempts:
2 left
💡 Hint
Check the array type and the types of elements inside.
✗ Incorrect
The array is declared to hold strings only, but 42 is a number. TypeScript raises a type error during compilation.
🔧 Debug
advanced2:00remaining
Why does this array type annotation cause a compilation error?
Identify the reason for the compilation error in this TypeScript code snippet.
Typescript
const values: Array<number> = [1, 2, "3", 4];
Attempts:
2 left
💡 Hint
Check the types of elements inside the array compared to the annotation.
✗ Incorrect
The array is typed as Array, but contains a string "3" which is not allowed. This causes a type error.
📝 Syntax
advanced2:00remaining
Which option correctly annotates an array of booleans in TypeScript?
Choose the correct TypeScript syntax to declare a variable named flags as an array of booleans.
Attempts:
2 left
💡 Hint
Remember the two common ways to annotate arrays in TypeScript.
✗ Incorrect
Option A uses the correct syntax boolean[] for an array of booleans. Option A misses the generic type parameter. Option A declares a tuple of one boolean, not an array. Option A assigns an array to a boolean variable.
🚀 Application
expert3:00remaining
How many items are in the resulting array after this TypeScript code runs?
Given the following TypeScript code, how many items does the variable result contain?
Typescript
const mixedArray: (string | number)[] = ["a", 1, "b", 2]; const result: string[] = mixedArray.filter((item): item is string => typeof item === "string");
Attempts:
2 left
💡 Hint
Look at the filter condition and the types in the original array.
✗ Incorrect
The filter keeps only strings from mixedArray. The original array has two strings: "a" and "b". So result contains 2 items.