TypeScript Interfaces
A TypeScript interface describes the shape of an object. It lists the property names and their types, so the compiler can check that every object you create or pass around matches that shape. Interfaces are one of the most-used features in real projects because they document data and catch mistakes early.
This tutorial covers how to define interfaces, add optional and readonly properties, describe function types, use index signatures, extend one or more interfaces, merge declarations, and implement an interface in a class. You will also see a clear comparison of interface vs type alias and the common excess property check error.
What Is a TypeScript Interface?
A TypeScript interface is a named contract that defines which properties an object must have and what type each property holds. It exists only at compile time. When the code compiles to JavaScript, the interface disappears completely.
Here is a simple example:
interface User {
name: string;
age: number;
}
const user: User = { name: "Riya", age: 28 };
console.log(user.name);
// Output: Riya
The user object must have a name string and an age number. If you leave one out or use the wrong type, the compiler reports an error before the code runs.
How Do You Define Object Shapes with an Interface?
An interface body lists properties as name: type pairs, separated by semicolons. You can include as many properties as you need. This shape is then reused everywhere the object travels, from function parameters to array elements.
interface Product {
id: number;
title: string;
price: number;
}
const item: Product = { id: 101, title: "Notebook", price: 60 };
console.log(item);
// Output: { id: 101, title: 'Notebook', price: 60 }
How it works: The Product interface describes three required properties. The object assigned to item must contain all three with the correct types. TypeScript does not create a class or a runtime object; it only checks the shape. The compiled JavaScript contains only the object literal.
How Do Optional and readonly Properties Work?
An optional property uses ? after the name and may be missing when you create the object. A readonly property cannot be reassigned after the object is created. Both are useful in real data, such as a nickname that may be empty or an id that must not change.
interface User {
readonly id: number;
name: string;
nickname?: string;
}
const user: User = { id: 1, name: "Arjun" };
user.name = "Arjun Kumar";
// user.id = 2;
// Error: Cannot assign to 'id' because it is a read-only property.
console.log(user.nickname ?? "no nickname");
// Output: no nickname
How it works: The id is readonly, so any assignment after creation fails at compile time. The nickname? is optional, so the object is valid without it. Reading user.nickname gives string | undefined, and the ?? operator provides a fallback. This pattern is everywhere in real projects.
How Do You Write a Function Type Interface?
An interface can describe a function type by listing the parameter types and the return type inside a call signature. You then use the interface as the type of a variable that holds a function.
interface Formatter {
(value: number): string;
}
const currency: Formatter = (value) => `Rs ${value}`;
console.log(currency(499));
// Output: Rs 499
How it works: The (value: number): string line is a call signature. Any function assigned to a Formatter must accept a number and return a string. The parameter value in the arrow function gets its type from the interface through contextual typing, so you do not need to write it again. If the function returned a number, the compiler would reject it.
What Are Index Signatures?
An index signature describes an object whose property names are not known in advance but whose values share a type. It looks like [key: string]: type. This is common for dictionaries, maps of settings, or lookup tables.
interface Scores {
[subject: string]: number;
}
const marks: Scores = {
maths: 92,
science: 88,
english: 75,
};
console.log(marks["science"]);
// Output: 88
How it works: The signature [subject: string]: number says every property key is a string and every value is a number. You can add any subject without changing the interface. A key with a non-number value would be rejected. Index signatures are useful, but they weaken type safety because a typo in a key still compiles, so use them for genuinely dynamic data.
How Do You Extend Interfaces?
An interface can extend another interface, which means it inherits all the properties and adds new ones. You can extend multiple interfaces at once, which lets you combine small pieces into a bigger shape. This keeps definitions focused.
interface Person {
name: string;
age: number;
}
interface Employee {
company: string;
salary: number;
}
interface Manager extends Person, Employee {
teamSize: number;
}
const manager: Manager = {
name: "Meera",
age: 35,
company: "Acme",
salary: 90000,
teamSize: 8,
};
console.log(manager);
// Output: { name: 'Meera', age: 35, company: 'Acme', salary: 90000, teamSize: 8 }
How it works: Manager extends both Person and Employee, so it must contain all five properties. If Person had an optional nickname, Manager would inherit that too. Multiple extension is a clean way to compose types without repeating property definitions.
What Is Declaration Merging?
Declaration merging means two interfaces with the same name in the same scope are combined into one. This is unique to interfaces; type aliases do not merge. It is used by libraries to let you add fields to an existing type.
interface Settings {
theme: string;
}
interface Settings {
fontSize: number;
}
const config: Settings = { theme: "dark", fontSize: 14 };
console.log(config);
// Output: { theme: 'dark', fontSize: 14 }
How it works: TypeScript sees two declarations of Settings and merges their properties. The resulting type has both theme and fontSize. This feature helps when you want to extend a library's interface from your own file without modifying the library. For most application code, prefer extends because merged declarations can be harder to track.
How Do Classes Implement Interfaces?
A class can implement an interface, which means the class promises to provide every property and method the interface describes. The compiler checks the class body against the interface.
interface Named {
name: string;
greet(): string;
}
class Student implements Named {
constructor(public name: string) {}
greet(): string {
return `Hello, I am ${this.name}.`;
}
}
const s = new Student("Anaya");
console.log(s.greet());
// Output: Hello, I am Anaya.
How it works: The implements Named clause tells TypeScript to check that Student has a name property and a greet method. The constructor(public name: string) shorthand creates the property automatically. If you removed greet, the compiler would report an error. You can learn more about class syntax in the Classes in TypeScript tutorial.
What Is the Excess Property Check Error?
When you assign an object literal to an interface-typed variable, TypeScript checks that every property in the literal is expected. This is called an excess property check. It catches typos and stale fields.
interface User {
name: string;
age: number;
}
// const user: User = { name: "Riya", age: 28, email: "r@x.com" };
// Error: Object literal may only specify known properties, and 'email' does not exist in type 'User'.
const user: User = { name: "Riya", age: 28 };
console.log(user.name);
// Output: Riya
How it works: The object literal includes email, which is not part of User. The compiler rejects the assignment. This check applies only to object literals. If the object comes from a variable of a wider type, extra properties are allowed by structural typing, because TypeScript only cares that the required properties exist. Add email to the interface if the field is legitimate.
Interface vs Type Alias: Which Should You Use?
| Feature | Interface | Type Alias |
|---|---|---|
| Describe object shapes | Yes | Yes |
| Union types | No | Yes |
| Extend multiple shapes | Yes (extends A, B) |
Yes (A & B) |
| Declaration merging | Yes | No |
| Implements in a class | Yes | Yes |
| Function types | Yes (call signature) | Yes |
| Best for | Object contracts, public APIs | Unions, mapped types, primitives |
A practical recommendation: use an interface for object shapes that may be extended or implemented, especially in public APIs. Use a type alias when you need unions, intersections, or mapped types. Both are valid, and teams often use both. The Type Aliases & Union Types tutorial covers the other side in depth.
Common Mistakes and Best Practices
- Using an interface for a union. Interfaces cannot represent
"yes" | "no". Reach for a type alias when you need a union, and keep interfaces for object shapes. - Forgetting the
?on optional fields. A required property forces every caller to supply it. If a field is genuinely optional in your data, mark it with?so callers are not forced to invent a value. - Assuming
readonlyprevents all changes.readonlyblocks reassignment of the property, but if the value is an object or array, its contents can still change. Usereadonlyarrays or deep-freeze patterns when full immutability matters. - Relying on index signatures for known data.
[key: string]: numberaccepts any key, so typos compile. Use explicit properties when the keys are known and reserve index signatures for dynamic maps. - Getting surprised by the excess property check. It only fires on object literals. Copying the same object into a variable first bypasses the check. Do not rely on this as a workaround; fix the interface instead.
Real-World Example: A User and Admin Model
This example brings together optional and readonly fields, interface extension, and the excess property error.
interface User {
readonly id: number;
name: string;
email: string;
nickname?: string;
}
interface Admin extends User {
permissions: string[];
}
const basicUser: User = {
id: 1,
name: "Rohit",
email: "rohit@example.com",
};
const admin: Admin = {
id: 2,
name: "Sana",
email: "sana@example.com",
nickname: "san",
permissions: ["users:read", "users:write"],
};
function display(user: User): void {
const nick = user.nickname ?? "none";
console.log(`#${user.id} ${user.name} (${nick})`);
}
display(basicUser);
display(admin);
// const broken: User = { id: 3, name: "A", email: "a@x.com", role: "admin" };
// Error: Object literal may only specify known properties, and 'role' does not exist in type 'User'.
// Output:
// #1 Rohit (none)
// #2 Sana (san)
How it works, line by line. The User interface has a readonly id, required name and email, and an optional nickname. The Admin interface extends User and adds a permissions array. The basicUser object omits nickname, which is allowed. The admin object includes it. The display function accepts a User, and because Admin extends User, an Admin object is also accepted. Inside, user.nickname ?? "none" handles the optional field safely. The commented line shows the excess property error: role is not in User, so the compiler rejects the literal. If you genuinely need a role, add it to the interface instead of removing the check.
Summary
- A TypeScript interface describes the shape of an object and disappears at compile time.
- Optional properties use
?; readonly properties block reassignment after creation. - Interfaces can describe function types with a call signature and dynamic objects with index signatures.
- Use
extendsto build larger interfaces from smaller ones, including multiple parents. - Declaration merging combines interfaces with the same name; classes can
implementan interface. - Prefer interfaces for object contracts and public APIs; use type aliases for unions and advanced types.
Now that you can model object shapes, continue to the Type Aliases & Union Types tutorial to learn how to create flexible types that combine several possibilities.
Frequently Asked Questions
When should I use an interface instead of a type alias?
Use an interface when you are describing the shape of an object that may be extended or implemented by a class, especially in a public API. Use a type alias when you need a union, an intersection, or a mapped type. Both work for simple object shapes, so pick the one that matches your team's style.
Can an interface have optional methods?
Yes. Write the method with a ? after its name, such as greet?(): string. Callers must check that the method exists before calling it, usually with if (obj.greet). The compiler then narrows the type and allows the call. This is useful for optional callbacks in configuration objects.
Why does TypeScript complain about an extra property in my object?
That is the excess property check. When you assign an object literal directly to an interface-typed variable, TypeScript rejects properties that are not in the interface. It catches typos and stale fields. To fix it, either remove the extra property or add it to the interface if it is genuinely part of the shape.
What is the difference between interface and class in TypeScript?
An interface exists only at compile time and describes a shape. A class exists at runtime and can create objects with methods and a constructor. A class can implement an interface to promise it matches the shape. Use an interface to describe data and a class when you need runtime behavior or instances.
Can I extend a type alias with an interface?
No, an interface can only extend another interface or a type that is statically known, such as an object type alias. It cannot extend a union type alias. If you need to build on a union, use an intersection type with a type alias instead of an interface.
Practice Exercises
Exercise 1 (Easy): Define a Basic Interface
Create an interface called Book with title: string, author: string, and pages: number. Create one object that matches it and print the title.
Show solution
interface Book {
title: string;
author: string;
pages: number;
}
const novel: Book = { title: "Wings", author: "A. Rao", pages: 320 };
console.log(novel.title);
// Output: Wings
The object must contain all three properties with the correct types, or the compiler reports an error.
Exercise 2 (Easy): Add Optional and readonly Fields
Extend the Book interface so subtitle is optional and isbn is readonly. Show that reassigning isbn produces an error.
Show solution
interface Book {
readonly isbn: string;
title: string;
subtitle?: string;
}
const novel: Book = { isbn: "978-93-000", title: "Wings" };
// novel.isbn = "978-93-001";
// Error: Cannot assign to 'isbn' because it is a read-only property.
console.log(novel.subtitle ?? "no subtitle");
// Output: no subtitle
The optional subtitle can be omitted, and the readonly isbn cannot be reassigned after creation.
Exercise 3 (Medium): Extend an Interface
Create Person with name and age. Create Employee that extends Person and adds company. Build an Employee object and print all fields.
Show solution
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
company: string;
}
const emp: Employee = { name: "Nisha", age: 29, company: "Acme" };
console.log(emp.name, emp.age, emp.company);
// Output: Nisha 29 Acme
Employee inherits name and age from Person, so the object must include all three properties.
Exercise 4 (Challenge): Index Signature and Interface Implementation
Create an interface Config with an index signature [key: string]: string. Create a class Settings that implements Config and stores the values in an object. Add two keys and print one.
Show solution
interface Config {
[key: string]: string;
}
class Settings implements Config {
[key: string]: string;
constructor(theme: string, lang: string) {
this.theme = theme;
this.lang = lang;
}
}
const s = new Settings("dark", "en");
console.log(s.theme);
// Output: dark
The index signature allows any string key with a string value. The class uses the same signature and assigns two keys in the constructor.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
