Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

TypeScript Arrays and Tuples: Typed Lists and Fixed Shapes

Typed Arrays

An array type describes the kind of values a list can contain. If a variable is typed as string[], TypeScript allows string operations on each item and prevents numbers, booleans, or unrelated objects from being added by mistake.

TypeScript supports two common array syntaxes: Type[] and Array<Type>. They mean the same thing for normal arrays. Most projects use Type[] for simple arrays because it is shorter and easy to read.

SyntaxMeaningExample
string[]Array of strings["html", "css"]
number[]Array of numbers[10, 20, 30]
Array<User>Array of user objects[{ id: 1, name: "Asha" }]
Array Type Syntax
const topics: string[] = ["types", "functions", "generics"];
const scores: Array<number> = [76, 88, 95];

topics.push("modules");
scores.push(100);

// topics.push(42);
// Error: number is not assignable to string.

const upperTopics = topics.map(topic => topic.toUpperCase());
console.log(upperTopics);

Arrays of Objects

Real applications usually store arrays of objects: users, products, posts, comments, invoices, lessons, and so on. Create a type or interface for the object shape, then use an array of that type.

This makes list operations safer. When you filter, map, reduce, or render the array, TypeScript knows exactly which properties exist on each item.

Array of Objects
type Tutorial = {
  id: number;
  title: string;
  category: "frontend" | "backend";
  published: boolean;
};

const tutorials: Tutorial[] = [
  { id: 1, title: "TypeScript Basics", category: "frontend", published: true },
  { id: 2, title: "Golang Modules", category: "backend", published: false },
];

const publishedTitles = tutorials
  .filter(tutorial => tutorial.published)
  .map(tutorial => tutorial.title);

console.log(publishedTitles); // ["TypeScript Basics"]

Readonly Arrays

A readonly array tells TypeScript that a function should not mutate the list it receives. This is useful for helper functions that only read data, because it prevents accidental calls to mutating methods like push(), pop(), splice(), or direct index assignment.

Readonly arrays do not make the original runtime array frozen. They are a compile-time promise that this particular reference will be used in a read-only way.

Read Without Mutating
function printTopics(topics: readonly string[]): void {
  topics.forEach((topic, index) => {
    console.log(`${index + 1}. ${topic}`);
  });

  // topics.push("new topic");
  // Error: push does not exist on readonly string[].
}

const courseTopics = ["setup", "types", "objects"];
printTopics(courseTopics);

Tuples

A tuple is an array with a fixed structure. Each position has a known type, and the order matters. Tuples are useful when a short positional result is clearer than creating a full object.

Named tuple elements make tuple code easier to understand because the type itself documents the meaning of each position. However, if the data has many fields or will be passed around widely, an object is usually easier to maintain.

Use a Tuple WhenUse an Object When
The result has two or three well-known positions.The result has several fields.
The order is obvious, such as [x, y].Property names make the code clearer.
The value is used locally and briefly.The value travels across modules or API layers.
Named Tuple Elements
type ApiResult = [statusCode: number, message: string];

function saveProfile(name: string): ApiResult {
  if (name.trim() === "") {
    return [400, "Name is required"];
  }

  return [200, "Profile saved"];
}

const [statusCode, message] = saveProfile("Neha");
console.log(statusCode, message);

Array Unions and Literal Values

Arrays can also contain union types. This is helpful when a list accepts a limited set of values, such as roles, statuses, directions, or filter options.

Combining arrays with literal types lets you model real options without allowing random strings. The compiler then catches typos before they reach the browser or server.

Array of Literal Union Values
type UserRole = "admin" | "editor" | "viewer";

const allowedRoles: UserRole[] = ["admin", "editor", "viewer"];

function canManageContent(role: UserRole): boolean {
  return role === "admin" || role === "editor";
}

const editableRoles = allowedRoles.filter(canManageContent);
console.log(editableRoles); // ["admin", "editor"]

// allowedRoles.push("owner");
// Error: "owner" is not part of UserRole.
Key Takeaways
  • Use Type[] or Array<Type> to describe array contents.
  • Arrays of objects become much safer when each object has a named type or interface.
  • Readonly arrays prevent accidental mutation through a specific reference.
  • Tuples model fixed-position values, but objects are better for larger structured data.
  • Literal union arrays are useful for roles, statuses, modes, and other controlled options.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.