0
0
Typescriptprogramming~15 mins

Generic functions with arrays in Typescript - Deep Dive

Choose your learning style9 modes available
Overview - Generic functions with arrays
What is it?
Generic functions with arrays are functions that can work with arrays of any type, like numbers, strings, or objects, without rewriting the function for each type. They use a special placeholder called a generic type to handle different data types safely. This means you write one function that adapts to many kinds of arrays. It helps keep your code clean and flexible.
Why it matters
Without generic functions, you would need to write many versions of the same function for different array types, which wastes time and can cause mistakes. Generic functions solve this by letting one function handle all types, making your code easier to maintain and less error-prone. This saves effort and helps programs work correctly with many kinds of data.
Where it fits
Before learning generic functions with arrays, you should understand basic functions, arrays, and TypeScript types. After this, you can learn about advanced generics, type constraints, and how generics work with classes and interfaces.
Mental Model
Core Idea
A generic function with arrays is like a recipe that uses a flexible ingredient placeholder, so it can make many dishes without changing the instructions.
Think of it like...
Imagine a cookie cutter that can shape dough into any cookie shape you want by swapping the cutter shape. The cookie cutter is the generic function, and the cookie shapes are the array types it works with.
Generic Function with Arrays

  function processArray<T>(arr: T[]): T[] {
    // work with arr of any type T
    return arr;
  }

  ┌───────────────┐
  │ processArray  │
  │  <T>          │
  └──────┬────────┘
         │
         ▼
  ┌───────────────┐
  │ Input: arr[]  │
  │ Type: T[]     │
  └──────┬────────┘
         │
         ▼
  ┌───────────────┐
  │ Output: T[]   │
  └───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding basic arrays
🤔
Concept: Learn what arrays are and how to use them in TypeScript.
An array is a list of items stored together. In TypeScript, you can create an array of numbers like this: const numbers: number[] = [1, 2, 3]; You can also have arrays of strings or other types: const names: string[] = ['Alice', 'Bob'];
Result
You can store and access multiple values of the same type in a single variable.
Knowing arrays is essential because generic functions often work with lists of data, and understanding their structure helps you manipulate them safely.
2
FoundationBasic functions with arrays
🤔
Concept: Write simple functions that take arrays as input and return arrays.
Here is a function that returns the first item of a number array: function firstItem(arr: number[]): number { return arr[0]; } This function only works with number arrays.
Result
You can get the first element from a number array using this function.
Functions that work with arrays are common, but limiting them to one type means you need many versions for different data types.
3
IntermediateIntroducing generic type parameters
🤔Before reading on: do you think a generic function can handle arrays of both numbers and strings without rewriting? Commit to your answer.
Concept: Use a generic type parameter to make a function work with any array type.
A generic type parameter is a placeholder for a type. We write it as before the function parameters: function identity(arg: T): T { return arg; } This function returns whatever it receives, no matter the type.
Result
The function can accept and return any type, making it reusable.
Understanding generic type parameters unlocks the ability to write flexible functions that adapt to many types without losing type safety.
4
IntermediateGeneric functions working with arrays
🤔Before reading on: do you think the generic function can return the same array type it receives? Commit to your answer.
Concept: Apply generic type parameters to functions that take arrays and return arrays of the same type.
Here is a generic function that returns the input array: function processArray(arr: T[]): T[] { return arr; } You can call it with different array types: const nums = processArray([1, 2, 3]); const strs = processArray(['a', 'b']);
Result
The function works with arrays of any type and returns the same type safely.
Using generics with arrays lets you write one function that handles many data types, reducing code duplication and errors.
5
IntermediateUsing generic functions with array methods
🤔Before reading on: can generic functions safely use array methods like map or filter on any array type? Commit to your answer.
Concept: Combine generic functions with common array methods to process data flexibly.
You can use array methods inside generic functions: function getFirstElement(arr: T[]): T | undefined { return arr[0]; } function mapArray(arr: T[], fn: (item: T) => U): U[] { return arr.map(fn); } Example: const lengths = mapArray(['apple', 'pear'], s => s.length);
Result
Generic functions can manipulate arrays with methods while keeping type safety.
Knowing how to combine generics with array methods lets you build powerful, reusable data processing functions.
6
AdvancedAdding type constraints to generics
🤔Before reading on: do you think you can limit generic types to only arrays of objects with certain properties? Commit to your answer.
Concept: Use constraints to restrict generic types to those that meet specific conditions.
Sometimes you want the generic type to have certain properties. You can add constraints: interface HasLength { length: number; } function logLength(arr: T[]): void { arr.forEach(item => console.log(item.length)); } This function only works with arrays of items that have a length property.
Result
You can safely use properties inside generic functions knowing the type meets requirements.
Type constraints prevent errors by ensuring generic functions only accept compatible types, improving code safety.
7
ExpertGeneric functions and type inference surprises
🤔Before reading on: do you think TypeScript always infers the generic type correctly when calling generic functions with arrays? Commit to your answer.
Concept: Explore how TypeScript infers generic types and when it might infer unexpected types with arrays.
TypeScript tries to guess the generic type from the arguments. But sometimes it infers a union or a broader type: const mixed = processArray([1, 'two', 3]); // inferred type: (string | number)[] This can cause unexpected behavior if you expect a single type. You can specify the type explicitly: const nums = processArray([1, 2, 3]);
Result
Understanding type inference helps avoid bugs and write clearer code.
Knowing how and when TypeScript infers types prevents subtle bugs and helps you control function behavior precisely.
Under the Hood
At runtime, generic types do not exist; they are erased by TypeScript. The compiler uses generics to check types during development but generates plain JavaScript functions that work with any data. This means generics provide safety and flexibility without extra code at runtime.
Why designed this way?
Generics were designed to allow code reuse and type safety without runtime overhead. TypeScript chose type erasure to keep JavaScript compatibility and performance, avoiding complex runtime type checks.
Generic Function Compilation Flow

  ┌───────────────┐
  │ TypeScript    │
  │ Source Code   │
  └──────┬────────┘
         │
         ▼
  ┌───────────────┐
  │ Type Checking │
  │ with Generics │
  └──────┬────────┘
         │
         ▼
  ┌───────────────┐
  │ Type Erasure  │
  │ Remove <T>    │
  └──────┬────────┘
         │
         ▼
  ┌───────────────┐
  │ JavaScript    │
  │ Output Code   │
  └───────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Do generic functions create different versions of the function for each type at runtime? Commit to yes or no.
Common Belief:Generic functions create separate copies of the function for each type used.
Tap to reveal reality
Reality:TypeScript compiles generic functions into a single JavaScript function without copies; generics exist only at compile time.
Why it matters:Believing this can lead to confusion about performance and code size, causing unnecessary optimization worries.
Quick: Can you use any property on a generic type without constraints? Commit to yes or no.
Common Belief:You can access any property on a generic type parameter without restrictions.
Tap to reveal reality
Reality:Without constraints, TypeScript does not allow accessing properties on generic types because it cannot guarantee they exist.
Why it matters:Ignoring this causes type errors and unsafe code, risking runtime crashes.
Quick: Does TypeScript always infer the most specific type for generic arrays? Commit to yes or no.
Common Belief:TypeScript always infers the exact type you expect for generic arrays automatically.
Tap to reveal reality
Reality:TypeScript sometimes infers a union or broader type if array elements differ, which may not match your expectations.
Why it matters:Misunderstanding inference can cause bugs or require explicit type annotations to fix.
Expert Zone
1
Generic functions with arrays can combine multiple generic parameters to transform data types, enabling complex data pipelines.
2
TypeScript's type inference can be guided with default generic types to simplify function calls while maintaining flexibility.
3
Using conditional types inside generic functions allows creating highly dynamic and type-safe array operations.
When NOT to use
Avoid generic functions when the function logic depends heavily on specific type details that generics cannot express. In such cases, use function overloading or specialized functions instead.
Production Patterns
In production, generic functions with arrays are used for utility libraries, data transformation pipelines, and API response handling, ensuring code reuse and type safety across diverse data shapes.
Connections
Polymorphism in Object-Oriented Programming
Both generics and polymorphism allow code to work with different types flexibly.
Understanding generics helps grasp polymorphism because both enable writing adaptable, reusable code that handles multiple data types.
Mathematical Functions
Generic functions abstract over types like mathematical functions abstract over numbers.
Seeing generics as abstract functions clarifies how they generalize operations beyond specific data types.
Biology: DNA as a Generic Blueprint
DNA uses a generic code to build many different proteins, similar to how generic functions use type placeholders to work with many data types.
Recognizing this parallel shows how abstraction and flexibility are fundamental in both programming and natural systems.
Common Pitfalls
#1Trying to access properties on a generic type without constraints.
Wrong approach:function printLength(arr: T[]): void { console.log(arr[0].length); // Error: Property 'length' does not exist on type 'T' }
Correct approach:interface HasLength { length: number; } function printLength(arr: T[]): void { console.log(arr[0].length); // Works safely }
Root cause:The generic type T could be anything, so TypeScript prevents unsafe property access without guarantees.
#2Assuming TypeScript infers the exact type for mixed arrays automatically.
Wrong approach:const result = processArray([1, 'two', 3]); // result inferred as (string | number)[] which may cause unexpected behavior
Correct approach:const result = processArray([1, 'two', 3]); // Explicitly specify union type to clarify intent
Root cause:TypeScript infers the broadest common type, which may not match the programmer's expectations.
#3Expecting generic functions to create multiple runtime copies for each type.
Wrong approach:function processArray(arr: T[]): T[] { // thinking this creates separate versions per T return arr; }
Correct approach:// Same function compiled once, generics erased at runtime function processArray(arr) { return arr; }
Root cause:Misunderstanding how TypeScript compiles generics leads to wrong assumptions about performance and code size.
Key Takeaways
Generic functions with arrays let you write one flexible function that works safely with many array types.
They use type placeholders called generics to keep code reusable and type-safe without rewriting for each type.
TypeScript removes generics at compile time, so they add no runtime cost but improve developer confidence.
Constraints on generics ensure you can safely use properties or methods on generic types.
Understanding type inference and when to specify types explicitly prevents subtle bugs in generic functions.