Level 5
Arrays & Objects
Type collections and structured data: array types, tuples, object type annotations, optional and readonly properties, and safe patterns for accessing nested data.
22 min read + quiz
Typing Arrays
An array of numbers is written number[], and an array of strings is string[]. There is an equivalent generic syntax, Array<number>, that means exactly the same thing; most style guides prefer the bracket form for simple types. Whichever you choose, TypeScript enforces homogeneity: every element must match the element type, and every value you read out is known to have that type.
This element-type knowledge flows through all the array methods. Calling .map on a string[] gives your callback a string parameter automatically; calling .filter returns another string[]. This is contextual typing at work, and it is why array-heavy code in TypeScript often needs almost no annotations.
Watch out for empty arrays: 'const items = []' gives TypeScript nothing to infer from, so the element type may end up as never or any depending on usage. When you create an empty array to fill later, annotate it: 'const items: string[] = []'.
const scores: number[] = [88, 92, 75];
scores.push(100);
// scores.push("high"); // Error: 'string' is not assignable to 'number'
// Methods know the element type:
const passed = scores.filter((s) => s >= 80); // s is number
const labels = scores.map((s) => "Score: " + s); // string[]
// Annotate empty arrays so inference has something to hold on to:
const queue: string[] = [];
queue.push("first");Element types are enforced on write and known on read, flowing through every array method.
Tuples: Fixed-Length, Mixed-Type Arrays
Sometimes a fixed number of positions matters more than a uniform element type: a coordinate pair is exactly two numbers, and a name-age record might be a string then a number. Tuples express this: [string, number] is an array with exactly those two slots in that order.
Tuples and arrays look identical at runtime; the distinction exists purely in the type system. TypeScript tracks each position separately, so element 0 of a [string, number] is a string, element 1 is a number, and accessing element 2 is a compile error.
Tuples appear all over real code: React's useState returns one, Object.entries produces them, and functions that need to return two values often use a tuple instead of an object. If your tuple grows past three elements, though, consider an object with named properties instead; position-based access gets hard to read.
type NameAndAge = [string, number];
const entry: NameAndAge = ["Ada", 36];
const who: string = entry[0]; // position 0 is string
const age: number = entry[1]; // position 1 is number
// entry[2]; // Error: no element at index 2
// Destructuring gives each part its correct type:
const [name2, age2] = entry;
console.log(name2.toUpperCase(), age2.toFixed(0));Each tuple position has its own type, and destructuring preserves them.
Object Types
Object types describe shape: which properties exist and what type each holds. You can write them inline, as in '{ title: string; pages: number }'. TypeScript then checks both directions: reading a property that does not exist is an error, and creating the object with a missing or wrongly-typed property is an error too.
TypeScript's checking is structural, not nominal: any object with the right properties satisfies the type, regardless of how or where it was created. This is different from Java or C#, where types match by declared name. Structural typing fits JavaScript's object-literal-heavy style perfectly.
One behavior surprises newcomers: excess property checking. When you assign an object literal directly to a typed target, TypeScript flags properties that the type does not mention, since a typo like 'colour' for 'color' is almost certainly a bug. The same object passed through an intermediate variable is allowed, because then the extra property might be intentional.
type Book = { title: string; pages: number };
const good: Book = { title: "TS Deep Dive", pages: 320 };
// Excess property check on direct literals:
// const bad: Book = { title: "Oops", pages: 100, publiher: "X" };
// Error: 'publiher' does not exist in type 'Book'. Typo caught!
// Structural typing: shape is what matters.
const data = { title: "Extra", pages: 200, isbn: "123" };
const alsoBook: Book = data; // OK via intermediate variableDirect object literals get strict excess-property checking - a powerful typo detector.
Optional and readonly Properties
Real-world objects often have properties that may be absent. Marking a property with ? ('subtitle?: string') makes it optional: objects may omit it, and reading it yields 'string | undefined', so the compiler forces a check before use. This mirrors optional function parameters and is the honest way to model incomplete data.
The readonly modifier prevents assignment after creation: a 'readonly id: string' can be set when the object is built but never overwritten. Like all TypeScript features, this is compile-time only, since the emitted JavaScript has no enforcement, but it reliably documents and protects intent within your codebase.
For safe access to optional and nested data, use optional chaining (?.) and nullish coalescing (??). 'book.subtitle?.toUpperCase()' short-circuits to undefined instead of crashing, and 'book.subtitle ?? "(none)"' supplies a fallback only when the value is null or undefined, unlike || which also overrides valid falsy values like 0 and empty strings.
type Article = {
readonly id: string;
title: string;
subtitle?: string;
};
const post: Article = { id: "a1", title: "Hello TS" };
// post.id = "a2"; // Error: cannot assign to 'id' - readonly
const sub = post.subtitle ?? "(no subtitle)";
console.log(sub); // "(no subtitle)"
console.log(post.subtitle?.length); // undefined, no crashOptional properties demand handling; readonly locks a property after creation.
Nested Structures and Index Signatures
Object types compose: a property's type can itself be an object type, an array of objects, or any combination. Complex nested annotations get unwieldy inline, which is one reason you will meet type aliases and interfaces in upcoming lessons; they let you name each layer and build big shapes from small ones.
When you do not know property names in advance, for example a dictionary mapping user IDs to scores, use an index signature: '{ [userId: string]: number }' means 'any string key maps to a number'. A cleaner built-in equivalent is Record<string, number>.
Be careful: with a plain index signature, TypeScript assumes every key you read exists, so 'scores["nobody"]' is typed number even though it is undefined at runtime. The compiler option noUncheckedIndexedAccess fixes this by typing such reads as 'number | undefined', which is safer and worth enabling in new projects.
type Team = {
name: string;
members: { name: string; role: string }[];
};
const team: Team = {
name: "Compilers",
members: [
{ name: "Ada", role: "lead" },
{ name: "Grace", role: "engineer" },
],
};
const scores: { [player: string]: number } = { Ada: 100 };
scores["Grace"] = 95;
console.log(team.members[0].name, scores["Ada"]);Nested object types and an index signature for dictionary-style data.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
What is the difference between number[] and [number, number]?
Question 2 · Find the error
This code fails to compile. What is wrong?
type User = { name: string; email: string };
const u: User = {
name: "Ada",
email: "ada@example.com",
admin: true,
};
console.log(u.name);Question 3 · Predict the output
What does this program print?
type Config = { retries?: number };
const config: Config = {};
const attempts = config.retries ?? 3;
console.log(attempts);Question 4 · True or false
A property marked readonly in TypeScript is also frozen at runtime - assigning to it from plain JavaScript throws an error.
Question 5 · Multiple choice