Skip to content

Interfaces

An interface describes the shape a value must have β€” which properties it needs, and their types β€” without providing any implementation. It’s a compile-time-only contract: any object matching the shape satisfies the interface, regardless of how it was created (this is called β€œstructural typing,” unlike the nominal typing of languages like C# or Java).

interface User {
name: string;
age: number;
email?: string; // optional property
}
function greet(user: User): string {
return `Hello, ${user.name}!`;
}
// No class needed -- a plain object matching the shape satisfies the interface
const alice: User = { name: "Alice", age: 30 };
greet(alice); // works
// Interfaces can extend other interfaces
interface Employee extends User {
employeeId: string;
}
// Interfaces can also describe function shapes
interface Comparator {
(a: number, b: number): number;
}
const byAge: Comparator = (a, b) => a - b;

Assuming an interface enforces that a value was created through a specific constructor or class β€” TypeScript’s structural typing means any object with a matching shape satisfies the interface, even if it has extra properties or came from somewhere else entirely.

interface Point { x: number; y: number; }
function distance(p: Point) {
return Math.sqrt(p.x ** 2 + p.y ** 2);
}
// Any object shaped like a Point works, even with extra properties
distance({ x: 3, y: 4, z: 5, label: "origin" }); // fine -- structurally compatible
// This surprises developers coming from nominally-typed languages,
// where you'd expect an explicit "implements Point" relationship
  1. Does an object need to explicitly declare implements SomeInterface to satisfy that interface in TypeScript?

    AnswerNo β€” TypeScript uses structural typing, so any object with a matching shape satisfies the interface automatically, with no explicit declaration required.
  2. What does a ? after a property name in an interface mean?

    AnswerThe property is optional β€” objects satisfying the interface may omit it.
  3. Can an interface describe a function’s call signature, not just an object’s properties?

    AnswerYes β€” interface Comparator { (a: number, b: number): number; } describes a callable shape, useful for typing callbacks.