Interfaces
Give an object shape a reusable name with the interface keyword.
Syntax
interface User { name: string; age: number; }An interface defines a named object shape you can reuse across your code. It keeps annotations short and self-documenting.
Defining one
Use the interface keyword followed by the shape. Then use the interface name as a type wherever you need that shape.
Interfaces are erased at compile time — they exist only to describe types.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A shared data contract for a User is defined as an interface and imported by both the API layer and the UI layer.
- An interface for a repository class enforces that every implementation provides the same CRUD method signatures.
- A library exports interfaces for its configuration options so consumers get IDE autocomplete when setting them up.
More examples
Define and use an interface
Defines a Product interface and uses it as both a function parameter type and a variable annotation.
interface Product {
id: number;
name: string;
price: number;
}
function displayProduct(p: Product): string {
return `${p.name} — $${p.price.toFixed(2)}`;
}
const pen: Product = { id: 1, name: 'Pen', price: 1.99 };
console.log(displayProduct(pen));Interface vs object literal type
Contrasts interfaces (which support declaration merging) with type aliases (which do not), a key structural difference.
// Interface — can be extended and merged
interface Animal {
name: string;
}
interface Animal {
legs: number; // declaration merging adds this
}
// Type alias — cannot be merged
type Point = { x: number; y: number };Interface for a function parameter
Uses an interface to give the options object of a search function a descriptive, reusable name.
interface SearchOptions {
query: string;
limit: number;
caseSensitive: boolean;
}
function search(opts: SearchOptions): string[] {
// implementation omitted
return [];
}
search({ query: 'ts', limit: 10, caseSensitive: false });
Discussion