Interfaces
Interfaces
Section titled βInterfacesβWhat it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβ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 interfaceconst alice: User = { name: "Alice", age: 30 };greet(alice); // works
// Interfaces can extend other interfacesinterface Employee extends User { employeeId: string;}
// Interfaces can also describe function shapesinterface Comparator { (a: number, b: number): number;}const byAge: Comparator = (a, b) => a - b;Common mistake
Section titled βCommon mistakeβ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 propertiesdistance({ 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" relationshipQuick practice
Section titled βQuick practiceβ-
Does an object need to explicitly declare
implements SomeInterfaceto satisfy that interface in TypeScript?Answer
No β TypeScript uses structural typing, so any object with a matching shape satisfies the interface automatically, with no explicit declaration required. -
What does a
?after a property name in an interface mean?Answer
The property is optional β objects satisfying the interface may omit it. -
Can an interface describe a functionβs call signature, not just an objectβs properties?
Answer
Yes βinterface Comparator { (a: number, b: number): number; }describes a callable shape, useful for typing callbacks.