0
0
Typescriptprogramming~3 mins

Why Generic array syntax in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could have one list that safely holds anything you want, without rewriting your code every time?

The Scenario

Imagine you have a box where you want to keep different types of toys: cars, dolls, and blocks. If you write separate lists for each toy type, it becomes messy and hard to manage.

The Problem

Writing separate lists for each type means repeating code and risking mistakes, like mixing toy types or forgetting to update all lists. It's slow and confusing, especially when you want to add new toy types.

The Solution

Generic array syntax lets you create one flexible list that can hold any type of toy safely. You write the list once, and it works for cars, dolls, blocks, or anything else, keeping your code clean and easy to update.

Before vs After
Before
let cars: number[] = [1, 2, 3];
let dolls: string[] = ['Anna', 'Elsa'];
After
let toys: Array<number | string> = [1, 2, 'Anna', 'Elsa'];
What It Enables

It enables you to write one reusable, type-safe list that adapts to any kind of data you want to store.

Real Life Example

Think of a toy store inventory system where you want to keep track of all items, whether they are cars, dolls, or blocks, in a single list without mixing up their types.

Key Takeaways

Generic arrays let you store any type safely in one list.

This avoids repeating code for each data type.

It keeps your code clean, flexible, and easy to maintain.