What if you could have one list that safely holds anything you want, without rewriting your code every time?
Why Generic array syntax in Typescript? - Purpose & Use Cases
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.
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.
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.
let cars: number[] = [1, 2, 3]; let dolls: string[] = ['Anna', 'Elsa'];
let toys: Array<number | string> = [1, 2, 'Anna', 'Elsa'];
It enables you to write one reusable, type-safe list that adapts to any kind of data you want to store.
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.
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.