Introduction to Interfaces
An Interface in TypeScript is a powerful structure that exclusively defines the conceptual shape of an object or a class map. They vanish completely when the code is transpiled to .js.
Defining an Interface
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
}
// Creating an object bound strictly to the User interface
const newSubmit: User = {
id: 1,
name: "Alice",
email: "alice@test.com"
// 'age' omitted because it's optional
};
readonly Properties
If an object property should never be altered after the object initializes (like database IDs), prefix it with readonly.
interface Product {
readonly _id: string; // Internal Database Mongo ID
title: string;
price: number;
}
const item: Product = {
_id: "6a89bxo9p",
title: "Keyboard",
price: 45
};
item.price = 50; // Works fine
// item._id = "new_id"; // TS ERROR: Cannot assign to '_id' because it is a read-only property.
When to use Interfaces?
There are two primary ways to create an object shape in TypeScript: interface and type (Type Alias).
Generally, standard practice dictates:
- Use
interfacewhenever you are constructing objects, especially objects communicating with databases or APIs. - Use
typewhen generating highly specific logical subsets, Tuples or specific Union strings (type Size = "Small" | "Large").