Last Updated : 11 Mar, 2025
TypeScript is a statically typed superset of JavaScript that adds optional types, classes, interfaces, and other features to help developers build robust and maintainable applications. One of the most powerful features of TypeScript is interfaces, which allow you to define the structure of objects, enforce consistency, and improve code readability.
What Are Interfaces?An interface in TypeScript is a contract that defines the structure of an object. It specifies the properties and methods that an object must have, without providing any implementation. Interfaces are used solely for type-checking purposes and are removed during the compilation process.
Why Use Interfaces?Here’s a simple example of how to use interfaces in TypeScript:
JavaScript
interface Car {
make: string;
model: string;
year: number;
}
const myCar: Car = {
make: "Toyota",
model: "Corolla",
year: 2022
};
console.log(myCar);
Output:
{
make: 'Toyota',
model: 'Corolla',
year: 2022
}
More Example of Interfaces in TypeScript
Interface in a Class JavaScript
interface Employee {
name: string;
age: number;
position: string;
}
class Manager implements Employee {
name: string;
age: number;
position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
}
const manager1 = new Manager("John Doe", 35, "Project Manager");
console.log(manager1);
Output:
Manager { name: 'John Doe', age: 35, position: 'Project Manager' }Interface for an Object JavaScript
interface Product {
id: number;
name: string;
price: number;
}
const product: Product = {
id: 1,
name: "Laptop",
price: 1200
};
console.log(product);
Output:
{ id: 1, name: 'Laptop', price: 1200 }Interface with Method Signatures JavaScript
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
class SimpleCalculator implements Calculator {
add(a: number, b: number): number {
return a + b;
}
subtract(a: number, b: number): number {
return a - b;
}
}
const calc = new SimpleCalculator();
console.log(calc.add(5, 3));
console.log(calc.subtract(9, 4));
Output:
8Best Practices for Using Interfaces
5
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4