October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Arrays of Objects in TypeScript: Declare, Type, and Use Them

Define an object shape, use it as an array’s element type, and choose between mutable arrays, readonly collections, tuples, and runtime validation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an array of consistently shaped records, define the object shape and use that type as the array’s element type: User[]. TypeScript also accepts the equivalent generic form Array<User>. The shape tells the type checker which properties each element should have; it does not validate or transform values at runtime.

Declare an array of objects with a named type

Define the record’s properties with an interface or a type alias, then append [] to that name for an array of those objects:

As an Amazon Associate I earn from qualifying purchases.

interface User {
  id: number;
  name: string;
  active: boolean;
}

const users: User[] = [
  { id: 1, name: "Ada", active: true },
  { id: 2, name: "Grace", active: false },
];

Each element must match the declared shape. For example, an entry with a string for id or without the required active property is incompatible with User. The TypeScript Handbook describes object shapes this way: “In TypeScript, we represent those through object types.” An object type may be anonymous or named with an interface or type alias; both named forms can describe the example above. Google’s TypeScript Style Guide prefers interfaces for object declarations as a house-style convention, not a language requirement. TypeScript Handbook: Object Types · Google TypeScript Style Guide

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the array syntax that reads clearly

User[] is shorthand for Array<User>; either expresses an array whose elements have the User type. The compact form is common for ordinary arrays, while the generic form can read more clearly inside complex or nested types.

Form What it expresses When it fits
User[] A mutable array with User elements Ordinary variables and parameters
Array<User> The same element relationship as User[] When the generic spelling reads more clearly in a complex type
Array<{ id: number; name: string }> An array whose elements have an inline object shape A one-off shape that does not need a reusable name
(User | Admin)[] An array where each element may be either a User or an Admin A collection intentionally containing either of two element types

Use parentheses around a union element type to make the intended grouping explicit. An inline shape is convenient when it is short and local; name it when you need to reuse it or want the collection’s contract to be easier to discuss. Google’s guide recommends T[] or readonly T[] for simple element types and Array<T> for more complex forms. That is a documented style convention, not a difference in TypeScript behavior. TypeScript Handbook: Object Types · Google TypeScript Style Guide

Use an annotation when the collection contract should be visible

An annotation such as const users: User[] = [...] makes the intended element type explicit and lets the checker flag incompatible entries. TypeScript can also infer a useful type from a well-shaped array literal, so a redundant annotation is not necessary on every local variable. Prefer a visible annotation where it clarifies an API or boundary; rely on inference when the type remains clear.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Once the collection is typed, property access and array methods are checked against its element type:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for (const user of users) {
  console.log(user.name);
}

const ids = users.map((user) => user.id);

const activeNames = users
  .filter((user) => user.active)
  .map((user) => user.name);

Here, user.name is typed as a string. But an array’s type does not guarantee that an element exists at every index: whether an indexed access is treated as possibly undefined depends on compiler options and settings. Use iteration or array methods when they fit the task, and account for an out-of-range index when accessing a particular position.

Use readonly when a function should not mutate the array

Annotate a parameter as readonly User[] or ReadonlyArray<User> when the function should read the collection without changing it through that reference:

function printUsers(users: readonly User[]) {
  for (const user of users) {
    console.log(user.name);
  }

  // users.push(...) is rejected by the type checker
}

A mutable array can be passed to a readonly array parameter, but a readonly array cannot be assigned to a mutable array type: doing so would permit mutation through a reference that promises not to allow it. This is a type-checking restriction, not a runtime freeze. It also does not make nested objects deeply immutable. Marking an object property readonly prevents reassignment of that property through the type, but does not automatically freeze the data it refers to. TypeScript Handbook: Object Types

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use tuples for fixed positions, not ordinary records

An array of objects is not the right shape for every collection. If the data is a fixed-position pair with different types—such as a name followed by a score—a tuple expresses the known positions and length:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const result: [string, number] = ["Ada", 98];

The first position is a string and the second a number. By contrast, User[] represents a variable-length collection whose elements share the same object shape. TypeScript Handbook: Object Types · TypeScript Handbook: Basic Types

Why object[] is usually too vague

The lowercase TypeScript type object means a non-primitive value; it does not say which properties a record must contain. It covers values other than primitives such as number, string, boolean, null, and undefined. An object[] annotation therefore does not provide a useful contract for fields such as id or name. For ordinary records, define the specific properties you expect instead. TypeScript Handbook: Basic Types

Validate external data at runtime

Type annotations describe values for the TypeScript checker; they do not check data arriving from an API, a file, or user input. In particular, payload as User[] is an assertion that asks the compiler to trust the programmer. It does not inspect, restructure, or validate the value, and it has no runtime effect.

For untrusted input, validate the actual value before treating it as User[]. A validator should check that the value is an array and that each entry has the required fields with the expected runtime types. Only after those checks succeed should the program rely on the User[] shape; a type assertion by itself is not a substitute for those checks. TypeScript Handbook: Basic Types

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.