TS: Types vs. Interfaces

RMAG news

A few days ago, we had a lively chat at work about how to type a package we’re working on.

In the middle of our discussion, someone threw out there:

“Interface and type, they’re basically the same, right?”

I was pretty taken aback! We ended up debating this a bit, and my colleague explained he meant that for a React app, it wouldn’t really matter whether we used types or interfaces for props or defining business models.

But actually, there are some important differences to keep in mind:

Type Aliases are super versatile.

You can use them for a bunch of different things like combining types, or defining arrays and tuples. No chance to implement that with interfaces:

type SomeType = a | b | string;
type Pair = [number, number];
type NamedVariable = (Input | Output) & { name: string };

Declaration Merging with Interfaces

One cool thing about interfaces is that you can add more details to them later through something called declaration merging. It’s like saying:

Hey, let’s add some more features to this existing interface
and you can do it anywhere in your code.

interface ICountry {
name: string;
capital: string;
}

interface ICountry {
population: number;
officialLanguage: string;
}

const france: ICountry = {
name: France,
capital: Paris,
population: 67000000,
officialLanguage: French
};

Intersection vs Extending

Last but not least important thing to know is that type intersection and interface extensions work differently

// It’s OK
type TUser = {
id: string;
}

type TUserData = TUser & {
id: number;
}

// Definitely not ok
/*
Interface ‘UserData’ incorrectly extends interface ‘User’.
Types of property ‘id’ are incompatible.
Type ‘number’ is not assignable to type ‘string’.
*/

interface User {
id: string;
}

interface UserData extends User {
id: number;
}

Some other details can be found at the section Differences Between Type Aliases and Interfaces

While my buddy thought there wasn’t much difference, knowing these details can help you decide which one to use and when. It may seem insignificant, but it’s good to know about it.

Finally, it doesn’t really matter whether you use interfaces or types for defining props or business entities in your React app. The key thing is just to make sure everyone on the team knows and follows the same rules you’ve set up.

Leave a Reply

Your email address will not be published. Required fields are marked *