iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Interfaces

An interface is a named description of a shape — what properties and methods a value has. They're TypeScript's main contract type.

Declaring & implementing

TS
interface Payable {
    total(): number;
    description: string;
}

class Invoice implements Payable {
    constructor(private amount: number, public description: string) {}
    total() { return this.amount * 1.10; }
}

Extending interfaces

TS
interface Named { name: string }
interface Aged  { age: number }
interface Person extends Named, Aged {
    greet(): string;
}

Optional & readonly members

TS
interface Config {
    readonly host: string;
    port?: number;
    log?: (msg: string) => void;
}

Function types

TS
interface Comparator<T> {
    (a: T, b: T): number;
}

const byAge: Comparator<{ age: number }> = (a, b) => a.age - b.age;

Index signatures

TS
interface StringDict {
    [key: string]: string;
}

Interface declaration merging

Interfaces with the same name in the same scope merge — handy for augmenting types from libraries:

TS
interface Window {
    myAppVersion: string;
}

window.myAppVersion;   // now typed (was missing before)

interface vs type

InterfaceType alias
extends with extendsextends with &
Declaration-mergesDoesn't merge
Slightly nicer error messagesMore expressive (unions, conditionals)
Best for object shapesBest for everything else (unions, primitives, mapped)
Tip: Use interface for "thing-shaped" types you might extend. Use type for unions, intersections, or conditional / mapped magic. Most projects mix both.

Example

Example
interface Payable {
  total(): number;
  description: string;
}

class Invoice implements Payable {
  constructor(private amount: number, public description: string) {}
  total() { return this.amount * 1.10; }
}
const i = new Invoice(100, 'Hosting');
console.log(i.description, i.total());
Try it Yourself »

Exercise

Keyword that wires a class to an interface.

class Invoice Payable {}

Test yourself

Q1. Interface declaration merging happens when…
Q2. A class implements an interface with…
Q3. Interface vs type alias — for object shapes…

Discussion

Loading…