Photo by Heidi Fin on Unsplash

How to Use Interface in Typescript: A Definitive Guide

The definitive guide from noob to pro

Alfredo Ryelcius
Published in
5 min readApr 12, 2023

--

TypeScript offers many benefits and features that can improve your JavaScript code. In this guide, we’ll explore how to use interfaces in TypeScript to write more robust and organized code.

This article will discuss one of the most fundamental and powerful features of TypeScript: interface.

What is TypeScript interface

interface is a keyword in TS to define the structure of an object, whether it is properties or methods. It is similar to interface in OOP languages, but less troublesome to set up.

Use interface to Define a Variable

inteface User {
email: string;
age: number;
address?: string;
}

The previous example demonstrates how to define an interface in TypeScript. In this example, we define properties for the contract that creates a User object, including the email, age, and address properties.

When using interfaces, appending ? after the property name denotes that the property is optional. If no value is assigned to an optional property, it defaults to undefined.

const user: User = {
email: 'hello@gmail.com',
age: 29,
}

The example demonstrates how to implement a TypeScript interface. One of the key benefits of using interfaces is that they enable IDEs to suggest and verify what can be done with objects. This allows developers to write code more efficiently and with fewer errors. For example:

// this will be underlined by IDE and will fail TS compilation
console.log(user.name)

// this will be okay
console.log(user.email) // "hello@gmail.com"
console.log(user.age) // 29
console.log(user.address) // undefined

Using interfaces to define function parameters can help prevent bugs by enforcing strict rules on how objects should be defined. Additionally, interfaces provide a self-documenting mechanism for code, making it easier to understand how objects should be structured.

Extend interface

Extending TypeScript interfaces is a powerful feature that enables developers to build more specific interfaces on top of existing ones.

This allows for a more modular and organized approach to defining interfaces, where common properties and methods can be shared across multiple interfaces.

To extend an interface, you simply use the extends keyword followed by the name of the interface you want to extend.

interface User {
userId: number;
email: string;
}

interface Admin extends User {
level: number;
}

// 'level: 10' will be underlined by IDE
const user: User = { userId: 10, email: "", level: 10 };
// OK
const admin: Admin = { userId: 10, email: "", level: 10 };

Use interface for Function Parameters

TypeScript functions are inherently typed, which means that each parameter must be defined with a specific type. However, when a function has many parameters, managing the order of those parameters can become challenging and error-prone.

// TOO MANY PARAMETERS
function sendEmail(
from: string,
to: string,
subject: string,
body: string,
attachments: string[]
): boolean {
// implementation goes here
return true;
}

To address this issue, one can use interfaces to create a well-defined contract for function parameters by grouping them together in an object, instead of defining each parameter individually.

interface Params {
from: string;
to: string;
subject: string;
body: string;
attachments: string[];
}

function sendEmail({ from, to, subject, body, attachments }: Params): boolean {
// implementation goes here
return true;
}

Using an interface to define function parameters can enhance the readability of the function implementation by making the parameter contract more explicit and organized.

Use TypeScript interface to Assign Function Return Type

TS function return value is also inherently typed. You can assign it yourself, or let TS decide what your function returns.

function add(x: number; y: number): number {
return x + y;
}

This is a simple example of how to add type to a function. Similar to using interface for function parameters, we can also use interface to specify the return type when our object properties get too many.

interface AccountData {
name: string;
email: string;
phone: string;
address: string;
accountNumber: string;
}

function getAccountData(): AccountData {
// retrieve data from database or API
const userData: AccountData = {
name: "John Smith",
email: "john.smith@example.com",
phone: "555-555-5555",
address: "123 Main St",
accountNumber: "123456789",
};
return userData;
}

The section below will introduce a more advanced TS concept called function signature.

Use TypeScript interface for Function Signature

A function signature in TypeScript is like a blueprint that tells TypeScript what kind of input a function needs, what it will output, and other important details.

By using function signatures, developers can write better code that is less likely to have bugs because they can ensure that the function is used correctly.

interface DataTransferObject {
query?: {};
body?: {};
response?: {};
}

function makeRequest<T extends DataTransferObject>({
query,
body,
}: Omit<T, "response">): T["response"] {
// make http call
const res = {};
return res as T["response"];
}

The previous example demonstrates how to define request body, query, and response when making an HTTP request using TypeScript interfaces. To use these interfaces, you can extend a base interface to create more specific interfaces for your needs.

interface GetAgeDto extends DataTransferObject {
query: {
userId: number;
};
response: {
age: number;
};
}

const res = makeRequest<GetAgeDto>({ query: { userId: 10 } });

console.log(res.age); // the type will be number

By extending the base interface, the new interface enforces the function to accept a query property, which is no longer optional. Additionally, the response will be typed according to the GetAgeDto interface.

In conclusion, using interfaces in TypeScript can greatly enhance the robustness, organization, and readability of your code.

By defining the structure and properties of objects, functions, and HTTP requests, interfaces provide a clear contract for how your code should be used and what it should do.

With interfaces, you can catch errors earlier in the development process, benefit from IDE suggestions and verification, and improve the overall quality of your code.

Read more about TypeScript:

--

--

Alfredo Ryelcius
CodeX
Writer for

TypeScript Geek during the day 👨🏻‍💻 Aspiring Writer at night ✍🏻 Writing about programming or maybe life lessons 🤷‍♂️