DEV Community

Cover image for Use Type, not Interface in TypeScript
Timi
Timi

Posted on

Use Type, not Interface in TypeScript

As we delve into the fascinating world of TypeScript, it becomes apparent that understanding and leveraging the nuances of type usage is pivotal to writing efficient and robust code. Today, we'll explore the critical distinction between using Type and Interface in TypeScript, and how this understanding can significantly impact the overall performance and maintainability of your projects.

TypeScript: A Brief Overview

Before we embark on our exploration of Type and Interface in TypeScript, let's take a moment to understand what TypeScript is and why it has become such a popular choice among developers.

TypeScript, developed by Microsoft, is a superset of JavaScript that introduces static typing capabilities. It allows developers to write strongly-typed code, catching errors at compile-time rather than runtime. This feature enhances code readability, maintainability, and overall productivity. As TypeScript transpiles into plain JavaScript, it can be effortlessly integrated into any existing JavaScript project.

Understanding Type and Interface

In TypeScript, both Type and Interface are used to define custom data types, but they serve distinct purposes. Let's look at each of them individually.

Type: Defining Unions, Intersections, and Aliases

With Type, we have the flexibility to create aliases for existing types, define unions or intersections of types, and even create complex data structures. It is particularly useful when dealing with scenarios that require combining multiple types or reusing them in various parts of the codebase.

Let's take an example to illustrate the power of Type:

type Pet = {
    name: string;
    age: number;
};

type Dog = Pet & {
    breed: string;
};

type Cat = Pet & {
    color: string;
};

function printPetInfo(pet: Pet) {
    console.log(`Name: ${pet.name}, Age: ${pet.age}`);
}

function printDogInfo(dog: Dog) {
    console.log(`Name: ${dog.name}, Age: ${dog.age}, Breed: ${dog.breed}`);
}
Enter fullscreen mode Exit fullscreen mode

In the above example, we define a Pet type and then create two additional types, Dog and Cat, by combining it with additional properties specific to each. This makes our code more organized, maintainable, and less prone to errors.

Interface: Extending Objects and Classes

On the other hand, Interface in TypeScript is primarily used for extending object shapes and classes. It allows us to specify the structure that an object must adhere to, providing a clear contract for the code.

Let's demonstrate the use of Interface with an example:

interface Shape {
    name: string;
    area(): number;
}

class Circle implements Shape {
    constructor(public radius: number) {}

    name = "Circle";

    area() {
        return Math.PI * this.radius * this.radius;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we define an Interface called Shape that mandates an object to have a name property and an area method. Then, we implement this Shape interface in a Circle class, ensuring that the Circle class adheres to the specified structure.

Best Practices: When to Use Type and Interface

Now that we comprehend the differences between Type and Interface, it's essential to understand when to use each of them to write more maintainable and performant code.

Use Type When:

  1. You need to create a union or intersection of multiple types.
  2. You want to create aliases for complex types to improve code readability.
  3. You are dealing with scenarios that require reusing types across the project.

Use Interface When:

  1. You want to specify the structure that an object must adhere to.
  2. You need to extend an object shape or class to ensure it adheres to a contract.
  3. You are defining the shape of an object that will be used by multiple classes or functions.

TypeScript's Type Inference: The Best of Both Worlds

One of the fantastic features of TypeScript is its powerful type inference mechanism. TypeScript can automatically infer the type of variables and expressions, reducing the need for explicit type annotations in most cases.

This brings the best of both Type and Interface worlds. When TypeScript can infer types correctly, you can rely on the concise and clean code without explicitly specifying types. However, in more complex scenarios, you can always fall back on Type and Interface to provide explicit type definitions.

Conclusion

In conclusion, TypeScript is a powerful language that empowers developers to write safer and more maintainable code by leveraging static typing. Understanding the appropriate usage of Type and Interface is essential in harnessing the full potential of TypeScript.

Remember, using Type is ideal when dealing with unions, intersections, and type aliases, while Interface excels at defining object shapes and class contracts. By applying these best practices, you can ensure that your TypeScript projects are not only efficient but also outrank others in search engine results.

Top comments (24)

Collapse
 
darkmavis1980 profile image
Alessio Michelini

While I agree on when to use interface or the types, I feel that the title was a bit clickbaity ;-)

Collapse
 
treasuredev_ profile image
Timi

I know, I don't want to be the one forcing everyone to use what they're not familiar with I want them to learn from each of them, and pick what suites them best 😉

Collapse
 
noblica profile image
Dušan Perković

Unless you need declaration merging, I don't really see a need to use interfaces?
Even in your class example, you can just as easily use a type with implements, it should work fine.

You can use types to define object shapes and class contracts just as well as interfaces.

I was hoping that the title of the post would reflect these differences a bit more. Instead this seems like more of an opinion piece.

Collapse
 
treasuredev_ profile image
Timi

I know the title sounds clickbaity but I had to teach them somehow. Also love the points you made about types Good one

Collapse
 
daguttt profile image
Daniel Gutierrez Muñoz

I was expecting the same.

Collapse
 
kgf profile image
Kenneth G. Franqueiro

Plenty of folks have already commented on the clickbait title, but I'd further note that the title pretty much directly contradicts TypeScript's own performance recommendations to use interfaces whenever possible.

github.com/microsoft/TypeScript/wi...

Collapse
 
rompeldunk profile image
Magnus Gule

Hmm. Good catch!

So basically when we using:

type Carnivore = {
meat: string;
}
type Cat = Pet & Carnivore {
color: string;
};

..we've already exceeded the general performance recommendations from MS of using type.

Collapse
 
kgf profile image
Kenneth G. Franqueiro

To make sure it's entirely clear: MS's recommendation is not to use type in this case, and instead express your example as an interface, which performs better, because interfaces are flattened and cached.

interface Cat extends Pet, Carnivore {
  color: string;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gktim profile image
gkTim

Good work!

Here another great article regarding this topic I came across yesterday: totaltypescript.com/type-vs-interf...

Collapse
 
alkadohs profile image
Alkado heneliko

The title doesn't reflect what's written here.

Collapse
 
steffennilsen profile image
Steffen Nilsen • Edited

Title suggest you should use type over interface, but the article fails to mention why the author case is making this case. I see superficial chatGTP like listings of the properties of type and interface before a conclusion is reached with no arguments for the title presented.

"By applying these best practices, you can ensure that your TypeScript projects are not only efficient but also outrank others in search engine results"

How using type or interface in my code is going to affect SEO is beyond me

Collapse
 
imamdev_ profile image
Imamuzzaki Abu Salam • Edited

Wow, your eye is good.
In my opinion, AI generated is actually OK. but, please review it first @treasuredev_ LOL 😂 It's misleading for someone who just believe it without checking the truthness of this information.

Collapse
 
aitchkhan profile image
Haroon Khan

ChatGPT

Collapse
 
daxtersky profile image
Miko

Clickbite title.

Collapse
 
treasuredev_ profile image
Timi

I know Brother, but they must now learn which is better for them

Collapse
 
harithzainudin profile image
Muhammad Harith Zainudin

Nice!

Collapse
 
treasuredev_ profile image
Timi

Thanks 🙏

Collapse
 
shameel profile image
Shameel Uddin

Clickbait title lol.
I came here seeing how interfaces was completely neglected. It appears it wasn't.

Collapse
 
barrymichaeldoyle profile image
Barry Michael Doyle

By applying these best practices, you can ensure that your TypeScript projects are not only efficient but also outrank others in search engine results.

How on earth does this make sense?

Collapse
 
jrfrazier profile image
WebDevQuest

Great explanation! You got me with the title.😄 Great execution.

Collapse
 
saidfatah profile image
ThePainter

I personally always use type since I code purely in the functionally programming paradigm so no classes in my projects .

Collapse
 
chideracode profile image
Chidera Humphrey

Nice article.

I learned a lot.

Collapse
 
dg_70ba62f1ee profile image
David Gottlieb

The reasons for one over the other are not compelling to use them as general rules. Especially the one saying if you need to share types across a project. Type doesn’t buy you anything additional.

Collapse
 
jimivi8846 profile image
Jimivi

What a misleading title, no doubt the quality of the platform has been decreasing with time because of such blogs!