TypeScript Lists
You're fetching user data from an API, and suddenly your app crashes because you tried to call .map() on undefined. Or maybe you're iterating through a product catalog and accidentally mutating the original array when you meant to create a copy. These are the kinds of bugs that happen when you don't have a solid grasp of how TypeScript arrays work.
TypeScript doesn't have a separate "List" type. Arrays are your lists, and they're dynamic, resizable, and packed with methods that make data manipulation straightforward. This guide will show you practical techniques for working with TypeScript arrays, from basic operations to advanced patterns you'll actually use in production code.
Creating and Handling Arrays in TypeScript
TypeScript gives you two ways to declare arrays: the bracket notation (type[]) or the generic syntax (Array<type>). Most developers prefer bracket notation because it's cleaner and more concise:
// Array literal with type annotation (preferred)
let statusCodes: number[] = [200, 404, 500];
// Generic syntax (more verbose)
let errorMessages: Array<string> = ["Not Found", "Server Error"];
// Empty array requires explicit typing
let apiResponses: Response[] = [];
Here's the key difference from JavaScript: TypeScript won't let you mix types unless you explicitly allow it. Trying to push a number into a string array fails at compile time, not runtime:
let userNames: string[] = ["alice", "bob"];
// Error: Argument of type 'number' is not assignable to parameter of type 'string'
userNames.push(123);
Basic Array Operations
Once you've created an array, you'll typically need to add, remove, or modify elements. Here are the essential operations:
let productCategories: string[] = ["electronics", "clothing"];
// Add elements
productCategories.push("furniture"); // Adds to end
productCategories.unshift("books"); // Adds to beginning
// Result: ["books", "electronics", "clothing", "furniture"]
// Remove elements
productCategories.pop(); // Removes last item: "furniture"
productCategories.shift(); // Removes first item: "books"
// Result: ["electronics", "clothing"]
// Modify with splice (position, deleteCount, ...items)
productCategories.splice(1, 0, "sports"); // Insert at index 1
// Result: ["electronics", "sports", "clothing"]
productCategories.splice(0, 1, "tech"); // Replace at index 0
// Result: ["tech", "sports", "clothing"]
To learn more about comprehensive array operations, check out the TypeScript array documentation. For more advanced array filtering techniques in Convex applications, see how to implement complex filters in Convex.
Effectively Using TypeScript Array Methods
Array methods are where TypeScript really shines for data manipulation. These higher-order functions let you transform, filter, and reduce data with clean, readable code. Let's look at the ones you'll reach for most often.
forEach() Method
The TypeScript forEach method executes a function for each array element. Use it when you need side effects (like logging, updating state, or making API calls) rather than transforming data:
interface ApiEndpoint {
url: string;
method: string;
}
let endpoints: ApiEndpoint[] = [
{ url: "/users", method: "GET" },
{ url: "/posts", method: "POST" },
{ url: "/comments", method: "DELETE" }
];
// Registering routes with a router
endpoints.forEach((endpoint, index) => {
console.log(`Registering route ${index + 1}: ${endpoint.method} ${endpoint.url}`);
// router.register(endpoint.method, endpoint.url);
});
map() Method
The TypeScript map method creates a new array by transforming each element. It's perfect for extracting properties, formatting data, or converting between types:
interface User {
id: number;
firstName: string;
lastName: string;
email: string;
}
let users: User[] = [
{ id: 1, firstName: "Sarah", lastName: "Johnson", email: "sarah@example.com" },
{ id: 2, firstName: "Mike", lastName: "Chen", email: "mike@example.com" }
];
// Extract just the data you need for a dropdown
let userOptions = users.map(user => ({
value: user.id,
label: `${user.firstName} ${user.lastName}`
}));
// Result: [{ value: 1, label: "Sarah Johnson" }, { value: 2, label: "Mike Chen" }]