Explain it simply
Interfaces, in plain language
An interface is a description of what an object must look like: which properties it has, what type each one is and which methods it offers. Think of a form with labelled fields; an object fits the interface if it fills in every required field with the right kind of value.
The interface itself does nothing at runtime. It is a promise the compiler checks while you write code, so a function that receives a User can rely on user.name existing and being a string.
Problem → Why → Solution
The problem: a contract that only exists in your head
A function prints user cards. In one place it is called with { name: "Alice", ID: 123 }, with ID in capitals, and in another with { nmae: "Bob", id: 7 }. In plain JavaScript both calls run and print undefined where data should be. The mistake is discovered when a customer sends a screenshot.
function printUser(user) { // implicitly any: nothing is checked
console.log(`User: ${user.name} (ID: ${user.id})`);
}
printUser({ name: "Alice", ID: 123 }); // User: Alice (ID: undefined)
printUser({ nmae: "Bob", id: 7 }); // User: undefined (ID: 7)Why nobody catches it
Nothing states which properties printUser needs, so neither the editor nor the compiler has an expectation to compare each call with. The contract lives only in the author's head. An interface writes that contract down where the compiler can check every call against it.
Core concept: a contract checked by shape
An interface lists the members an object must have. Each property has a name and a type. A ? after the name (is_admin?: boolean) makes it optional, which also adds undefined to its type, and readonly prevents reassignment after the object is created. Methods are written as signatures without a body, such as greet(): string: the interface says what exists, not how it works.
TypeScript checks interfaces structurally. An object satisfies User if it has all of User's required members with compatible types; it does not need to be declared as a User or built by a special constructor. If it has a name and an id, it is a User. A value with extra properties that arrives through a variable is still accepted as a User.
One exception catches beginners: excess property checks. When you write an object literal directly where an interface is expected, TypeScript also rejects properties the interface does not know, because an unknown property in a fresh literal is almost always a typo, like isAdmin for is_admin. The same object stored in a variable first passes, since it may legitimately be used elsewhere.
What the compiler accepts for printUser(user: User)
---------------------------------------------------
interface User { name: string; id: number; is_admin?: boolean }
printUser({ name: "Ann", id: 1 }) OK
printUser({ name: "Ann" }) error: id is missing
printUser({ name: "Ann", id: "1" }) error: id is a number
printUser({ name: "Ann", id: 1, isAdmin: true }) error: excess property
const u = { name: "Ann", id: 1, team: "web" }
printUser(u) OK: not a fresh literalInterfaces can build on each other with extends: interface Admin extends User { permissions: string[] } has everything User has, plus permissions. Like aliases, interfaces are erased when compiled, so you cannot use them with instanceof or to validate JSON at runtime.
For dictionary-like objects whose keys you do not know in advance, use an index signature: interface Scores { [player: string]: number } says every string key holds a number. scores["Aung"] = 12 is fine, while scores["Aung"] = "twelve" is a compile error. When the keys are fixed, naming each property is safer, because an index signature also lets you read keys that do not exist.
- Write the contract: interface User
- Mark optional (?) and readonly parts
- Compiler compares shapes, not names
- Erased at runtime: no checks there
An interface is a shape promise checked at compile time, not a runtime validator.
General pattern
interface Name {
required: Type;
optional?: Type; // may be missing
readonly fixed: Type; // cannot be reassigned
method(param: Type): Result;
}
interface Child extends Name {
extra: Type;
}
const value: Name = { /* every required member */ };Write each property as name: Type, add ? for optional and readonly to block reassignment. extends takes every member of an existing interface and adds new ones.
A User contract
The example declares a User interface, uses it as a parameter type and passes in an object that matches the contract.
interface User {
name: string;
id: number;
is_admin?: boolean; // Optional property
}
function printUser(user: User) {
console.log(`User: ${user.name} (ID: ${user.id})`);
}
let myUser: User = { name: "Alice", id: 123 };
printUser(myUser);Code breakdown
- Lines 1-5
interface User {Declares the contract: two required properties, name (string) and id (number).
- Line 4
is_admin?: boolean; // Optional propertyThe ? makes it optional: the object on line 11 leaves it out and still type-checks. Reading user.is_admin gives boolean | undefined.
- Line 7
function printUser(user: User) {The parameter is typed with the interface, so inside the function the editor autocompletes name and id and flags typos like user.nmae at once.
- Line 11
let myUser: User = { name: "Alice", id: 123 };The annotation checks the literal. Adding isAdmin: true here would be an excess property error, and leaving out id would be a missing property error.
- Line 12
printUser(myUser);The compiler already knows myUser is a User, so the call is safe and prints User: Alice (ID: 123).
User: Alice (ID: 123)Extending interfaces, and interface vs type alias
Reuse a base shape with extends instead of repeating it. Method signatures are declared just like properties, and reassigning a readonly property is a compile error.
interface Entity {
readonly id: number;
createdAt: Date;
}
interface Product extends Entity {
name: string;
price: number;
discount?: number; // percent
label(): string;
}
const book: Product = {
id: 1,
createdAt: new Date("2026-01-15"),
name: "TypeScript Basics",
price: 20,
label() {
return `${this.name} - $${this.price}`;
},
};
console.log(book.label()); // TypeScript Basics - $20
// book.id = 2; // error: Cannot assign to 'id' because it is a read-only property| Need | interface | type alias |
|---|---|---|
| Describe an object shape | yes | yes |
| Union, literal or tuple | no | yes |
| Build on another shape | extends | & (intersection) |
| Reopen to add members | yes (declaration merging) | no |
In practice either works for object shapes; being consistent within a project matters more. A common team rule is interface for object shapes and type aliases for unions and everything else.
In real projects
Real project: contracts for dependencies
Real code bases use interfaces in two places most of all. First, API contracts between frontend and backend: interfaces such as OrderResponse live in a shared package that both client and server import. Second, contracts for the dependencies a service relies on. The checkout code does not know the real payment provider, only a PaymentGateway interface. Thanks to structural typing, a test simply passes in a fake object with that shape:
interface PaymentGateway {
charge(amountCents: number, customerId: string): Promise<string>;
}
const fakeGateway: PaymentGateway = {
async charge(amountCents, customerId) {
return `fake-receipt-${customerId}-${amountCents}`;
},
};
async function checkout(gateway: PaymentGateway, total: number): Promise<void> {
const receipt = await gateway.charge(total, "cus_42");
console.log("Receipt:", receipt);
}
checkout(fakeGateway, 1999); // Receipt: fake-receipt-cus_42-1999In production you pass a real object that calls the provider's SDK, without changing a single line of checkout. Switching providers later means writing one new object that matches the interface. And when you add a method to the interface, the compiler flags every implementation that does not have it yet, so you know exactly what to update.
Common mistakes
Common mistakes
1. Hiding an excess property error with as
When you see "Object literal may only specify known properties", it is tempting to silence it with { ... } as User. The error usually points at a typo such as isAdmin versus is_admin. Fix the property name, or add the property to the interface if it is really needed.
2. Treating an optional property as always present
With discount?: number, strict mode rejects price * (1 - product.discount / 100), because discount may be undefined; in plain JavaScript that calculation would return NaN. Supply a default such as product.discount ?? 0.
3. Expecting an interface to check runtime data
const user: User = await res.json() compiles because json() returns any; nothing has been checked. Validate outside data with a runtime check such as the type guards from the previous lesson. Note too that readonly is shallow: with readonly tags: string[], tags.push() still works.
Best practices
Best practices
- Keep interfaces as small as their users need; if a function only needs name, do not demand the whole object.
- Make fields that should never change after creation, such as id and createdAt, readonly.
- Give optional properties a default with ?? or a check when you read them.
- Follow one rule across the project: interfaces for object shapes, type aliases for unions.
Mini challenge
A library shelf
Write an interface for books and an e-book interface that extends it, then describe every book on a shelf and add up the pages.
- The Book interface has readonly isbn, title, author, pages and an optional borrowedBy.
- EBook extends Book and adds fileSizeMb: number.
- describeBook(book) returns "Title by Author (N pages) - available" or "- borrowed by Name".
- totalPages(books) adds up every book's pages.
- Put an EBook into a Book[] array to show structural compatibility.
// TODO: interface Book (readonly isbn, title, author, pages, optional borrowedBy)
// TODO: interface EBook extends Book (adds fileSizeMb)
function describeBook(book: Book): string {
// TODO: "available" when nobody borrowed it, else "borrowed by <name>"
return "";
}
function totalPages(books: Book[]): number {
// TODO: add up the pages
return 0;
}
// TODO: create one Book and one EBook, put both in a Book[] and print the resultsExpected: Three lines: "Dune by Frank Herbert (412 pages) - available", "Learning TS by Mya Mya (250 pages) - borrowed by Ko Aung" and "Total pages: 662".
Show hint
book.borrowedBy is string | undefined, so a truthiness check can choose the status. For totalPages, try reduce((sum, b) => sum + b.pages, 0).
Show solution
interface Book {
readonly isbn: string;
title: string;
author: string;
pages: number;
borrowedBy?: string;
}
interface EBook extends Book {
fileSizeMb: number;
}
function describeBook(book: Book): string {
const status = book.borrowedBy ? `borrowed by ${book.borrowedBy}` : "available";
return `${book.title} by ${book.author} (${book.pages} pages) - ${status}`;
}
function totalPages(books: Book[]): number {
return books.reduce((sum, b) => sum + b.pages, 0);
}
const novel: Book = { isbn: "978-1", title: "Dune", author: "Frank Herbert", pages: 412 };
const guide: EBook = {
isbn: "978-2",
title: "Learning TS",
author: "Mya Mya",
pages: 250,
borrowedBy: "Ko Aung",
fileSizeMb: 4.2,
};
const shelf: Book[] = [novel, guide]; // an EBook is also a Book
shelf.forEach((b) => console.log(describeBook(b)));
console.log(`Total pages: ${totalPages(shelf)}`);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An interface describes an object's properties, types and methods as a contract the compiler checks.
- ? makes a property optional and readonly blocks reassignment, shallowly.
- TypeScript compares shapes, and only fresh object literals get excess property checks.
- extends lets interfaces reuse each other, and every interface is erased at runtime.
TypeScript Handbook — TypeScript