Skip to main content
TypeScript provides powerful tools for working with objects and arrays, including interfaces for type definitions and methods for safe copying.

Defining Object Types with Interfaces

Interfaces define the shape of objects in TypeScript:
interface Person {
    firstName: string;
    lastname: string;
    age: number;
    address?: Address; // Optional property
}

interface Address {
    postalCode: string;
    city: string;
}
The ? symbol marks optional properties. address? means the property can be omitted.

Creating Objects

Once you define an interface, you can create objects that match its structure:
const ironman: Person = {
    firstName: 'Tony',
    lastname: 'Stark',
    age: 45
};

const spiderman: Person = {
    firstName: 'Peter',
    lastname: 'Parker',
    age: 22
};

Working with Arrays

TypeScript arrays can be typed to ensure they only contain specific types:
const myArray: number[] = [1, 2, 3, 4, 5, 6];

Copying Arrays Safely

Use structuredClone() to create a deep copy of an array:
const myArray: number[] = [1, 2, 3, 4, 5, 6];
const myArray2 = structuredClone(myArray);

myArray2.push(7);

console.log({ myArray, myArray2 });
// myArray: [1, 2, 3, 4, 5, 6]
// myArray2: [1, 2, 3, 4, 5, 6, 7]
Avoid using the spread operator [...array] for nested objects or arrays - it only creates a shallow copy. Use structuredClone() for deep copies.

Array Type Annotations

There are two ways to annotate array types:
// Bracket notation (preferred)
const numbers: number[] = [1, 2, 3];

// Generic notation
const strings: Array<string> = ['a', 'b', 'c'];
The bracket notation (number[]) is more concise and is the recommended style in most TypeScript codebases.

Type Safety Benefits

TypeScript prevents you from adding wrong types to arrays:
const myArray: number[] = [1, 2, 3];
myArray.push(4);      // ✓ Valid
myArray.push('five'); // ✗ Error: Type 'string' not assignable to 'number'

Object vs Interface

Interfaces are the preferred way to define object shapes in TypeScript because they:
  • Provide better error messages
  • Can be extended and composed
  • Support optional properties naturally

Build docs developers (and LLMs) love