Comparing Intersection and Interface Extends in TypeScript
One common question is whether to use type
or interface
in TypeScript.
To clarify the difference, type
can represent anything, including objects, whereas interface
primarily represents object types.
Given the significance of object types in TypeScript and the broader context of JavaScript,
Transcript
00:00 Comparing types and interfaces is something I get asked about all the time. Should I use type or should I use interface? Because if you think about it, type can represent an object. Type can represent anything, whereas interface can only really represent object types. Object types are obviously big in TypeScript and very, very important.
00:17 A lot of what you'll do in JavaScript will be object based, but also unions are pretty big and useful in TypeScript. So you might think about type and interface like that. I've got a big resource on types and interface that I'll keep up to date, which you can look at down below.
00:33 But I want you to actually think about the difference between intersections, the ampersand symbol, and interface extends. It turns out that TypeScript prefers it when you can to use interface extends. That's because you remember all of the interfaces that we had, like with ID, with created at, user and product.
00:52 TypeScript knows that you can really just like, it can cache those with its name there. And when you use an interface, it kind of like caches it on that name. So on the username and then everywhere it's used, it references that cache.
01:07 Whereas when you use intersections, it really has to compute it almost every time it's used because the intersection is kind of quite complicated and difficult to figure out. So TypeScript recommends where you can to use interface extends over intersections.
01:22 But if you're just using kind of like basic types, like type props for a React component or something, then it actually doesn't matter too much whether you use interface or type. In fact, I've got another article, which you can also read below on what you should use for React props too, because that's an interesting discussion all by itself.
01:42 So types versus interfaces, that's going to come up, I think, a few times during the course of this whole course. Really, you should be thinking about interface extends versus intersections. And in the example that we've already seen just here, I would pretty much always use interface extends because it's just a little bit more expressive.
01:59 And it means that TypeScript can cache it a little bit better performance wise. So it will run slightly faster when you're doing your type checking and when your ID is kind of updating based on your code.