Interfaces

An interface describes the shape of an object — what properties it has and what types they are — without saying anything about where that object comes from. Any object with a matching shape satisfies the interface, whether or not it was ever explicitly declared to.

Defining and using an interface

TS user.ts
interface User {
  name: string;
  age: number;
}

function describe(user: User) {
  return `${user.name} is ${user.age} years old`;
}

const alice: User = { name: "Alice", age: 30 };
console.log(describe(alice));
Output
Alice is 30 years old

describe doesn't care how alice was created — it only cares that whatever gets passed in has a name: string and an age: number. This is called structural typing: TypeScript checks shape, not declared identity.

Optional and readonly properties

TS optional.ts
interface Product {
  readonly id: number;
  name: string;
  discount?: number;
}

const item: Product = { id: 1, name: "Mug" };
console.log(item.discount);

item.id = 2;
tsc output
optional.ts:8:1 - error TS2540: Cannot assign to 'id'
because it is a read-only property.

discount?: number means the property can be left out entirely — accessing it when it's missing gives undefined rather than an error. readonly id means the property can be set once, when the object is created, and never reassigned afterward.

Extending an interface

TS extend.ts
interface Animal {
  name: string;
}

interface Dog extends Animal {
  breed: string;
}

const rex: Dog = { name: "Rex", breed: "Labrador" };
console.log(`${rex.name} is a ${rex.breed}`);
Output
Rex is a Labrador
Note: because TypeScript checks shape rather than identity, an object doesn't need any implements keyword or explicit declaration to satisfy an interface — if it has the right properties, it qualifies, even if it was built somewhere else entirely for a different purpose. This trips up developers coming from Java or C#, where a class has to explicitly declare which interfaces it implements. It also means passing an object with extra, unrelated properties usually still works, as long as the required ones are present.