Why use Type and not Interface in TypeScript

preview_player
Показать описание

Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).

👉 Discord: all my courses have a private Discord where I actively participate

⏱️ Timestamps:
0:00 Type Alias vs Interface
2:05 Interface problem 1
3:15 Interface problem 2
4:05 Interface problem 3
5:39 Interface problem 4
6:49 Consideration
7:34 Interface problem 5
9:41 Interface problem 6
11:49 Classes
12:33 Best arguments!
12:47 Arguments pro interface

#typescript #typescripttutorial
Рекомендации по теме
Комментарии
Автор

My rule of thumb is use interface until type is needed. 90% of the times I find myself defining objects

godin
Автор

I use interface for objects (which is mostly what I do when defining data models) and type for all else as needed. I don't think they're mutually exclusive. Use them both.

jerusso
Автор

They may do similar things but the concept they convey is different. I use interface as the meaning of the interface that there is in Java/C# or other OOP languages, that is something a class needs to implement. While type is like a struct/record, something that is only used to pass around data, not methods.

This way in my opinion the codebase is clear, since you have a separation between two concepts.

alerighi
Автор

I don't really consider these to be problems... I consider them different use cases. Type I use when aliasing.. Interfaces I use when defining an interface. Call it semantics - because it mostly is. I actually consider the fact that interfaces only define object shapes to be a benefit, it's generally pretty rare that I want to simply alias an underlying / primitive type other than as a placeholder when passing it around. Quite often I'd alias a string as EmailAddress for example but usually because I'm passing the type around and at some point I suspect I may want to replace that type alias with a proper interface without replacing all the areas where the type is passed (of course you have to change the places that actually operate on the type).
It's far more common that I want to define a contract for an object so I'm happy using interfaces as that's what they are. I also actually prefer the syntax as it conveys more info (seems more expressive) saying "interface IDerivedThing extends IBaseThing {...}" rather than "type IDerivedThing = IBaseThing & {...}".

fredhair
Автор

Interface is for shapes in the form of objects, you can "extend" a shape. With shapes you can build a hierarchy.
Type alias is for type composition. you can compose types from simple types. A type is a fixed definition. You can change/omit properties with the help of utility types.

hansschenker
Автор

Wrote this reply in another reply thread, but essentially it's to answer some people who complain to just use interfaces until you can't. I create an example hypothetical scenario to showcase why this is unnecessary in this reply:

I favor always using types just like Wesley explains in this video, because essentially it keeps everything consistent. If you really have the specific case for more complex interface polymorphism, e.g. complex hybrid types, then you will already know you should use interfaces and create that exception. If not, every other case you can use types and make it consistent.

To say you use interfaces until type is needed is like saying, if we bridge the example to declaring variables, that when you define an object u do:

const obj = { example: 'example string' }

and when you "know" you need to not use an object you just use another way of declaring:

dec loggedIn = false

In this situation, "dec" is a made-up replacement for const / let that stands for "declare variable", where you know you are declaring a variable that is not an object. This is the same as the interface type situation, but if you can do:

dec obj = { example: 'example string' }

why would u keep switching between dec and const... just use dec all the time.

Now back to the video, it's the same with types and objects. If I need a union I use type = type1 | type2 | type3 etc or some type like type = AnotherType[] or type = typeof keyof Anothertype, and if I needed to type an object I have to suddenly swap to interface or vice versa it's just messy. Just always use types, just like you can always use const, even if they add a new keyword to declare variables with objects to allow you to do very specific things that aren't needed often you would still continue to use const to declare both objects and other stuff.

krantinebhwani
Автор

I disagree. Interfaces has limited functions for a reason. It makes it clearer to understand what the code is intended for at first glimpse. Having lack of features is an advantage in this case when it comes to readability.

I'm afraid that junior developers will now haphazardly add 'type' to their code after watching this video.

AqgvPr-hqvu
Автор

That's because interfaces are... well, interfaces. They represent a contract - a set of methods and properties exposed by the object. They are not types. If types were only for primitives, interfaces would make much more sense in TS.
Btw, you can create an interface for a primitive too like this: interface Address extends InstanceType<typeof String> {}; It is just not as convenient as with types :)

ivorybanana
Автор

One point in favor of interface is that it can extends from both type alias and interface. A type alias can extends (intersects) from types but cannot from interfaces. When working with third party libs that export props as interfaces, this might be an issue if you strictly use type alias in your project

tiagoc
Автор

This knowledge is extremely useful when you're fixing someone else's code. You would understand the working 'intent' more clearly (or quicker) knowing the utility and restrictions of each facility. Thanks for the review & lesson.

GeorgeMonsour
Автор

As a person who new on this typescript world, your video is really understandable. Thank you.

adhec
Автор

Funny thing is that this video convinced me to use interface over type unless necessary :)

mojito
Автор

While it might be debatable what to use, but this is the first time I understood the difference between interface and type. Thanks for that!

DebopriyoBasu
Автор

Most of these "problems" assume that interfaces and types are exclusive, which they are not! Just because you decide to prefer interfaces to define your objects doesn't mean that you must limit yourself and not use types to solve all those use cases. Only problem 6 really touches on a "problem" of interfaces, everything else was never something interfaces were meant to solve. Interfaces are meant for objects, and types can do objects too, a far more interesting video topic would be to ask "for objects, should I use interfaces or types?". Aside from problem 6 (which is mostly solvable by avoiding global types which is a bad practice anyway imo), this video doesn't really provide any arguments for one or the other.

Worx
Автор

i prefer interfaces honestly because they feel more strict and the extend keyword feels more clean and i find the most complex features of types not really necessary. And ofc interfaces are a concept that exists in other languages. I only use type when i need the union feature. In my company I work on a massive react project with ts and most devs prefer interfaces it gets the work done.

billy
Автор

This is a misleading title! Types are not a silver bullet and there are plethora of articles out there explaining it better than I could ever do. As with everything, use the right tool for right problem! It is that simple. I mean, there is even an eslint rule (called "prefer-interface") that is part of the "recomended" config that suggests you to use interface where possible.

davidhavl
Автор

Videodakileri göz önüne aldığımızda evet 'type' daha cazip görünebilir ama tam olarak böyle olmasada nesne tabanlı bir programlama dili kullanıyoruz. Verilerle çalıştığımızda nesne odaklı gitmek daha mantıklı olduğu için 'interface'in daha mantıklı buluyorum. 'interface' kullanıyorken daha kontrollü ve daha profesyonel ilerlediğimde 'type'a göre çok daha verimli olduğunu düşünüyorum.

Kısa olması önemli değil, önemli olan işlevi :D Açıkçası, bence 'interface' daha iyi.

thetanertube
Автор

One uses interfaces if they wish to flip the dependencies of a system around, mainly in OO environments like C++, C#, and Java. Javascript has the rule of composition over definition;Javascript follows structural comparison rules and doesn't really care about structural definition comparisons (is it of the same direct type or is it a child of one).

Because objects in js follow different rules for substitution, interfaces aren't really as needed in the same way they are needed in the earlier mentioned environments. In js, expecting an object of a type with a function validate means it can be any object as long as their validate matches the expected function header (and even that doesn't have to be true).

Typescript interfaces are a bit weird. They are nice, but types are indeed a better alternative.

LordErnie
Автор

I still prefer interfaces for simple object shapes or anything that contains a function, so it can be used to implement into a class instance. Types for anything more complicated when dealing with plain objects. That's my rule.

gosnooky
Автор

I'm going with interface always, type for everything else interface can't. So I have a nice distinction without any confusion.

khoanhn