- Abstract class
- Annotations
- Array
- Asserts
- Class
- Const
- Decorators
- Default parameter
- Dictionary
- Enum
- For loop
- forEach()
- Function
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Operator
- Optional parameter
- Promise
- Property
- Tuples
- Type alias
- Type guard
- Type narrowing
- Union
- Utility types
- Var
- Void
TYPESCRIPT
TypeScript Array: Syntax, Usage, and Examples
A TypeScript array is a collection of elements of a specific type. You use it to store lists of data—strings, numbers, objects, or even other arrays—with all the safety and support that TypeScript's static typing provides.
How to Use Arrays in TypeScript
You can declare arrays in TypeScript in two main ways. Both offer type safety and help your editor catch bugs early.
Using type[]
Syntax
let numbers: number[] = [1, 2, 3];
This defines an array of numbers. You can only push or assign numeric values.
Using Array<type>
Syntax
let colors: Array<string> = ['red', 'green', 'blue'];
This format is helpful in generic functions or when working with more complex types.
You can choose either style. Both create a strongly typed TypeScript array that can help reduce runtime errors.
When to Use Arrays in TypeScript
You’ll use arrays in TypeScript every time you need to store multiple values. Some common use cases include:
- Managing lists of items in apps: users, products, tasks
- Working with API responses that return arrays of objects
- Creating helper functions like filters, mappers, and reducers
- Organizing components or options in a UI
- Sorting or chunking data for pagination or search
Because arrays are flexible and efficient, they show up in nearly every project. The array TypeScript structure lets you define their shape clearly and avoid mismatches.
Examples of Arrays in TypeScript
Array of Objects in TypeScript
You can create arrays of custom object types:
interface Product {
id: number;
name: string;
}
const products: Product[] = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Phone' }
];
This array in TypeScript
ensures every object matches the Product
interface. TypeScript will flag any missing or mistyped properties.
Conditionally Add Object to Array in TypeScript
Sometimes, you want to push a value only if a condition is true:
let cart: string[] = ['apple'];
const addItem = (item: string, shouldAdd: boolean) => {
if (shouldAdd) {
cart.push(item);
}
};
addItem('banana', true);
This is useful in forms, filters, and toggles where the data changes based on user actions.
TypeScript Array Type for Readability
If you’re reusing a structure, give it a name:
type UserList = Array<{ id: number; name: string }>;
const users: UserList = [
{ id: 1, name: 'Jo' },
{ id: 2, name: 'Alex' }
];
Creating an alias like this keeps your code cleaner and easier to read.
Learn More About Arrays in TypeScript
Array Methods: map, filter, reduce
All the JavaScript array methods work with TypeScript arrays, but with added type safety.
const prices: number[] = [10, 20, 30];
// Map example
const withTax = prices.map(price => price * 1.1);
// Filter example
const expensive = prices.filter(price => price > 15);
// Reduce example
const total = prices.reduce((sum, price) => sum + price, 0);
Because each method knows the type of data in the array, you get better editor suggestions and fewer mistakes.
TypeScript Get Even-Spaced Items in Array
Let’s say you want to pull every third item from a list:
function getEvenlySpaced<T>(arr: T[], step: number): T[] {
return arr.filter((_, index) => index % step === 0);
}
const result = getEvenlySpaced(['a', 'b', 'c', 'd', 'e', 'f'], 2);
// ['a', 'c', 'e']
This kind of function is helpful when creating pagination or working with visualization data.
TypeScript Array of Type With Union
You can define arrays that accept multiple types using union types:
let mixedArray: (string | number)[] = ['hello', 42, 'world'];
You get flexibility while still controlling what kinds of data are allowed.
TypeScript Last Item in Array
Getting the last item is easy and safe:
const items = [1, 2, 3, 4];
const last = items[items.length - 1];
Want to be extra safe? Write a helper that returns undefined
for empty arrays:
function getLast<T>(arr: T[]): T | undefined {
return arr.length ? arr[arr.length - 1] : undefined;
}
This pattern prevents errors in components that rely on array data.
Use readonly
for Immutable Arrays
If you don’t want others modifying your array:
const days: readonly string[] = ['Mon', 'Tue', 'Wed'];
// days.push('Thu'); // Error!
Use this in shared state, constants, or APIs where immutability matters.
TypeScript Arrays With Generics
Arrays play well with generic functions:
function wrapInArray<T>(item: T): T[] {
return [item];
}
const result = wrapInArray('hello'); // type is string[]
You can use this in utility libraries or reusable components.
Check Array Length and Emptiness
Before using an array, always check if it's empty:
if (myArray.length === 0) {
console.log('No items found');
}
Or write a helper:
function isEmpty<T>(arr: T[]): boolean {
return arr.length === 0;
}
Simple patterns like this help prevent silent errors.
Looping Over Arrays
You can use for
, for...of
, or forEach()
:
const letters = ['a', 'b', 'c'];
for (const letter of letters) {
console.log(letter);
}
You can also grab both value and index:
letters.forEach((letter, index) => {
console.log(`${index}: ${letter}`);
});
Looping styles in TypeScript are as flexible as in JavaScript—but with type checking on your side.
Best Practices for Arrays in TypeScript
- Always define a specific type: avoid using
any[]
unless absolutely necessary. - Use interfaces or type aliases when working with arrays of objects.
- Leverage array methods like
map
,filter
, andreduce
instead of mutating loops. - Use readonly arrays for constants or shared state to prevent accidental changes.
- Use optional chaining and null checks before accessing array elements.
- Prefer
const
overlet
for arrays that won't be reassigned.
A TypeScript array gives you all the power of JavaScript arrays—plus the confidence of knowing exactly what’s inside. Whether you’re handling lists of data from an API, creating reusable utilities, or building dynamic interfaces, arrays in TypeScript help keep your code safe, expressive, and easy to maintain.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.