The best way to organize your Typescript interfaces

The best way to organize your Typescript interfaces

ยท

3 min read

If you work or have worked with Typescript you probably faced a bunch of times where you had to create interfaces. Commonly people create those interfaces on the fly where they need to use it.

This practice really adds up to the problem of readability, maintenance, reusability and clean coding. In this article I will show how I like to organize my interfaces. You will see how easy it is and how it adds up to the clean coding strategy.

Usually we have two types of interfaces. The ones we use on objects and the others we use on classes. This is how I like to organize them:

Screen Shot 2020-11-26 at 19.35.56.png

And the object interface often look something similar to this one:

export default interface IGithubObject {
    full_name: string;
    description: string;
    html_url: string;
    forks: number;
    stargazers_count: number;
    open_issues: number;
    owner: { login: string; avatar_url: string };
}

The class interface is somewhat similar to this:

export default interface IService {
    execute(): never;
}

That is it! You have organized your interfaces and you can start using them...

How do I use them?

it is as simple as importing them wherever you need, like so:

import IGithubObject from '../interfaces/objects/IGithubObject';

const githubObject: IGithubObject = {
    full_name: "full name";
    description: "description";
    html_url: "some url";
    forks: 3;
    stargazers_count: 3;
    open_issues: 4;
    owner: { login: "login username"; avatar_url: "some url" };
}

And if you want to make a class implement that interface you just need to do something like this:

import IService from '../interfaces/classes/IService';

export default class MyService implements IService{
     execute(): never {
          console.log('this is my implementation');
     }
}

Now you can make use of the intellisense to see class methods and object fields plus your interfaces are reusable now.

I hope this tutorial suits you well and please don't forget to support it by slapping the like button now. ๐Ÿ˜€

See you on the next post.