TYPESCRIPT
TypeScript Interface: Syntax, Usage, and Examples
A TypeScript interface defines the structure of an object by specifying property names and their expected types. Interfaces help enforce consistency across different parts of your code without generating additional JavaScript.
What Is an Interface in TypeScript?
An interface in TypeScript is a way to define the expected shape of an object. Unlike classes, interfaces do not generate JavaScript code; they exist purely for type-checking during development.
interface User {
name: string;
age: number;
isAdmin: boolean;
}
let user: User = {
name: "Alice",
age: 30,
isAdmin: false,
};
Here, the User
interface ensures every user object has a name
, age
, and isAdmin
property with the correct types.
How to Use TypeScript Interfaces
Define an Interface
You can define an interface using the interface
keyword:
interface Product {
id: number;
name: string;
price: number;
}
Now, any object assigned to this type must match the specified structure.
Implement an Interface in a Class
A class can implement an interface to enforce structure:
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Woof!");
}
}
The Dog
class must include a name
property and a makeSound
method, as required by Animal
.
Extend an Interface
You can extend an existing interface to add more properties.
interface Employee {
name: string;
id: number;
}
interface Manager extends Employee {
department: string;
}
let teamLead: Manager = {
name: "John",
id: 101,
department: "Engineering",
};
The Manager
interface includes all properties from Employee
and adds department
.
Use an Interface to Define Function Parameters
You can pass an interface as an argument to a function.
interface Person {
firstName: string;
lastName: string;
}
function getFullName(person: Person): string {
return `${person.firstName} ${person.lastName}`;
}
let user = { firstName: "Jane", lastName: "Doe" };
console.log(getFullName(user)); // Output: Jane Doe
When Should You Use TypeScript Interfaces?
Enforce Consistency
Interfaces make sure all objects follow a consistent structure. If you accidentally omit a required property, TypeScript throws an error.
interface Car {
brand: string;
year: number;
}
let myCar: Car = { brand: "Toyota" }; // Error: Property 'year' is missing
Improve Code Readability
By defining clear object shapes, interfaces help other developers understand your code more easily.
Enable Type Safety in Function Parameters
Using interfaces in function parameters ensures valid data structures:
interface Order {
productId: number;
quantity: number;
}
function processOrder(order: Order) {
console.log(`Processing order for product ${order.productId}, quantity: ${order.quantity}`);
}
Examples of TypeScript Interfaces
Use an Interface for an Array
You can declare an array of objects using an interface.
interface Book {
title: string;
author: string;
}
let books: Book[] = [
{ title: "The Hobbit", author: "J.R.R. Tolkien" },
{ title: "1984", author: "George Orwell" },
];
Use Optional Fields in Interfaces
You can make properties optional by adding ?
after the property name.
interface User {
name: string;
email?: string; // Optional property
}
let user1: User = { name: "Alice" };
let user2: User = { name: "Bob", email: "bob@example.com" };
Define a Function Signature in an Interface
Interfaces can describe function shapes.
interface MathOperation {
(x: number, y: number): number;
}
let add: MathOperation = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
TypeScript Pass Interface as Argument
You can use interfaces as function arguments to enforce object structure.
interface Student {
name: string;
grade: number;
}
function printStudent(student: Student) {
console.log(`${student.name} is in grade ${student.grade}`);
}
printStudent({ name: "Lily", grade: 10 });
Declare an Array of Type Interface
You can declare an array of objects conforming to an interface.
interface Task {
id: number;
title: string;
}
let tasks: Task[] = [
{ id: 1, title: "Learn TypeScript" },
{ id: 2, title: "Build a project" },
];
TypeScript Model Class vs. Interface
A model class includes both data and behavior, while an interface only defines the structure.
interface Vehicle {
brand: string;
}
class Car implements Vehicle {
brand: string;
constructor(brand: string) {
this.brand = brand;
}
drive() {
console.log(`${this.brand} is driving`);
}
}
Use an interface for type-checking and a class when you need logic inside your objects.
TypeScript Interface Default Value
Interfaces do not support default values directly, but you can use a factory function.
interface Config {
theme: string;
darkMode?: boolean;
}
function createConfig(config: Config = { theme: "light" }): Config {
return { darkMode: false, ...config };
}
console.log(createConfig()); // { theme: 'light', darkMode: false }
TypeScript Extend Interface
You can extend an interface to create specialized types.
interface Animal {
species: string;
}
interface Cat extends Animal {
meow(): void;
}
let kitty: Cat = {
species: "Feline",
meow: () => console.log("Meow!"),
};
kitty.meow(); // Output: Meow!
TypeScript Implement Interface
Classes can use interfaces to enforce a contract.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string) {
console.log(`Log: ${message}`);
}
}
let logger = new ConsoleLogger();
logger.log("Hello, world!");
TypeScript Interface Inherit
Interfaces can inherit from multiple interfaces.
interface Engine {
horsepower: number;
}
interface Wheels {
count: number;
}
interface Car extends Engine, Wheels {
brand: string;
}
let myCar: Car = { brand: "Tesla", horsepower: 300, count: 4 };
TypeScript Interface Array
You can create an interface for array elements.
interface Person {
name: string;
age: number;
}
let people: Person[] = [
{ name: "Eve", age: 28 },
{ name: "Mike", age: 35 },
];
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.