Bird
Raised Fist0
Typescriptprogramming~10 mins

Generic array syntax in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generic array syntax
Declare generic type T
↓
Create array of type T
↓
Add elements of type T
↓
Access elements as type T
↓
Use array with type safety
This flow shows how to declare a generic array type, add elements, and access them with type safety.
Execution Sample
Typescript
function printArray<T>(arr: T[]): void {
  for (const item of arr) {
    console.log(item);
  }
}

printArray<number>([1, 2, 3]);
This code defines a generic function to print elements of an array of any type, then calls it with a number array.
Execution Table
StepActionEvaluationResult
1Declare generic function printArray<T>T is generic typeFunction ready to accept array of any type
2Call printArray<number> with [1, 2, 3]T is numberArray type is number[]
3Start loop over array elementsitem = 1Print 1
4Next loop iterationitem = 2Print 2
5Next loop iterationitem = 3Print 3
6Loop endsNo more elementsFunction returns void
💡 Loop ends after all elements are printed
Variable Tracker
VariableStartAfter 1After 2After 3Final
arrundefined[1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3]
itemundefined123undefined
Key Moments - 3 Insights
Why do we write <T> after the function name?
The <T> declares a generic type parameter so the function can work with any type, as shown in step 1 of the execution table.
What does T[] mean in the function parameter?
T[] means an array where every element is of type T, ensuring type safety when accessing elements, as seen in steps 3-5.
Why do we specify <number> when calling the function?
Specifying <number> tells TypeScript that T is number here, so the array must contain numbers, matching the argument type in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'item' at step 4?
A1
B2
C3
Dundefined
💡 Hint
Check the 'Evaluation' column at step 4 in the execution table.
At which step does the loop finish iterating over the array?
AStep 3
BStep 5
CStep 6
DStep 2
💡 Hint
Look for the step where the 'Loop ends' action happens in the execution table.
If we change the call to printArray<string>(["a", "b"]), what changes in the execution table?
AThe type T becomes string and array elements are strings
BThe loop will not run
CThe function will print numbers instead
DNo change at all
💡 Hint
Refer to step 2 where T is set to number; changing to string changes T and array type.
Concept Snapshot
Generic array syntax in TypeScript:
- Use <T> to declare a generic type parameter.
- Use T[] to type an array of elements of type T.
- Functions can accept arrays of any type safely.
- Specify type when calling, e.g., printArray<number>([1,2,3]).
- Ensures type safety and flexibility.
Full Transcript
This lesson shows how to use generic array syntax in TypeScript. We declare a generic type parameter T using angle brackets after the function name. Then we use T[] to type an array of elements of that type. The example function printArray<T> takes an array of type T and prints each element. When calling the function, we specify the type, like number, so the array must contain numbers. The execution table traces each step: declaring the function, calling it with a number array, looping over elements, printing each, and ending the loop. The variable tracker shows how the array and loop variable change. Key moments clarify why we use <T>, what T[] means, and why we specify the type when calling. The quiz tests understanding of variable values during loop, loop termination step, and effect of changing the generic type. This concept helps write flexible and type-safe code with arrays in TypeScript.

Practice

(1/5)
1. Which of the following is a correct way to declare an array of numbers using generic array syntax in TypeScript?
easy
A. let nums: number = [1, 2, 3];
B. let nums: Array<number> = [1, 2, 3];
C. let nums: Array = [1, 2, 3];
D. let nums: number[] = 123;

Solution

  1. Step 1: Understand generic array syntax

    In TypeScript, Array<Type> declares an array holding elements of Type.
  2. Step 2: Check each option for correct syntax and type

    let nums: Array<number> = [1, 2, 3]; uses Array<number> with a number array, which is correct. Others have wrong types or assignments.
  3. Final Answer:

    let nums: Array<number> = [1, 2, 3]; -> Option B
  4. Quick Check:

    Generic array syntax = Array<Type> [OK]
Hint: Use Array<Type> or Type[] for arrays [OK]
Common Mistakes:
  • Forgetting to specify the type inside Array<>
  • Assigning a non-array value to an array type
  • Using Array without type parameter
2. Which of the following is the correct syntax to declare an array of strings using the shorthand syntax in TypeScript?
easy
A. let names: string[] = ['Alice', 'Bob'];
B. let names: Array = ['Alice', 'Bob'];
C. let names: string = ['Alice', 'Bob'];
D. let names: [string] = ['Alice', 'Bob'];

Solution

  1. Step 1: Recall shorthand array syntax

    In TypeScript, Type[] declares an array of Type.
  2. Step 2: Validate each option

    let names: string[] = ['Alice', 'Bob']; correctly uses string[] for an array of strings. Others are incorrect or incomplete.
  3. Final Answer:

    let names: string[] = ['Alice', 'Bob']; -> Option A
  4. Quick Check:

    Shorthand array syntax = Type[] [OK]
Hint: Use Type[] for quick array declarations [OK]
Common Mistakes:
  • Omitting the type inside Array<>
  • Using tuple syntax instead of array
  • Assigning array to a non-array type
3. What will be the output of the following TypeScript code?
function firstElement<T>(arr: Array<T>): T | undefined {
  return arr[0];
}

const nums: number[] = [10, 20, 30];
console.log(firstElement(nums));
medium
A. Error
B. undefined
C. 10
D. 30

Solution

  1. Step 1: Understand the generic function behavior

    The function firstElement returns the first element of the array or undefined if empty.
  2. Step 2: Apply function to given array

    The array nums has elements [10, 20, 30], so arr[0] is 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    firstElement([10,20,30]) = 10 [OK]
Hint: Generic function returns first array item or undefined [OK]
Common Mistakes:
  • Assuming function returns last element
  • Confusing undefined with zero
  • Thinking generic causes error
4. Identify the error in the following TypeScript code snippet:
let fruits: Array<string> = ['apple', 'banana', 5];
medium
A. The array contains a number instead of a string
B. Array<string> syntax is invalid
C. Missing semicolon at the end
D. Array should be declared as string[]

Solution

  1. Step 1: Check array element types

    The array is declared to hold strings only.
  2. Step 2: Identify type mismatch

    The element 5 is a number, which violates the string type constraint.
  3. Final Answer:

    The array contains a number instead of a string -> Option A
  4. Quick Check:

    Array<string> must hold only strings [OK]
Hint: Array type must match all element types [OK]
Common Mistakes:
  • Mixing types inside a typed array
  • Ignoring type errors in arrays
  • Confusing syntax errors with type errors
5. You want to create a function in TypeScript that accepts an array of any type and returns a new array with the same elements repeated twice. Which is the correct generic array syntax for the function parameter and return type?
hard
A. function repeatArray<T>(arr: Array): Array<T>
B. function repeatArray(arr: T[]): T[]
C. function repeatArray<T>(arr: T): T[]
D. function repeatArray<T>(arr: Array<T>): Array<T>

Solution

  1. Step 1: Define generic parameter and array type

    The function uses a generic type T and takes an array of T elements.
  2. Step 2: Ensure return type matches input array type

    The function returns an array of T, so Array<T> is correct for both parameter and return type.
  3. Final Answer:

    function repeatArray<T>(arr: Array<T>): Array<T> -> Option D
  4. Quick Check:

    Generic function array syntax = Array<T> [OK]
Hint: Use <T> and Array<T> for generic array functions [OK]
Common Mistakes:
  • Omitting generic type parameter <T>
  • Using non-generic Array without type
  • Incorrect parameter or return types
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard