Become a TypeScript Wizard with Matt's upcoming TypeScript Course: www.totaltypescript.com/ Follow Matt on Twitter / mattpocockuk
Жүктеу.....
Пікірлер: 277
@hugodsa89 Жыл бұрын
Finally someone actually highlighted that Interfaces have different features from types. Good bless this man.
@Issvor
Жыл бұрын
I'm just learning TS and pretty much most basic tutorials or articles I've found just say "types and interfaces do the same thing", so this video definitely caught me by surprise
@benjidaniel5595
Жыл бұрын
Interfaces really only have 1 feature, interface merging. Types can do everything else and much more
@kentlarsson1263
Жыл бұрын
I think its varied a lot over the development of Typescript what they can do, which probably adds to the confusion. Personally I think it was a mistake in the language design to have two things for this.
@BrunoOliveira-lm6wl
Жыл бұрын
@@benjidaniel5595 Not only 1, but they also handle conflicts much sooner than what you would get with types. But as a general rule I use types most of the time, I like to think of types with unions and intersections much more than with interfaces.
@treyrader
3 ай бұрын
Bytegrad does too sorta. Mostly he just discusses how to achieve the same results though. His take away is that it's best to be consistent so chose one vs the other. Gets interesting when you use shadcn though since all of its boilerplate is extended with interface
@JonathanRose24 Жыл бұрын
This is my preferred approach. Use types by default, and interfaces only when necessary. I find type intersections and unions to be very useful
@happyfase
Жыл бұрын
But when is it necessary?
@JeyPeyy
Жыл бұрын
@@happyfase I think when you need to extend global types, such as the Window type. Or extending a library (or creating a library which should be possible to extend) I suppose.
@DemanaJaire
Жыл бұрын
@@happyfase Tell me you haven't watched the video without telling me that you haven't watched the video.
@vukkulvar9769
Жыл бұрын
I find interfaces to be much cleaner when reading errors. Especially when there is a lot of properties.
@davidstephen7070
Жыл бұрын
@@happyfase use interface if you think the implementation type will have multiple version. Like general type animal thing. Like walk, fly and swim. Walk speed each animal can be differend. not all animal can fly. not all animal can swim too deep.
@marcomow Жыл бұрын
When the video is the normal distribution meme with the newbie and the guru saying "use types by default" btw great content as always, love that you took on this journalistic effort, it's perfect to keep the pulse on TS world. Thank you!
@bobthemagicmoose Жыл бұрын
I use interfaces for classes and types for everything else... so yeah, I never use interfaces 😉
@alichamas63
Жыл бұрын
Well that's just lovely
@imagineabout4153
Жыл бұрын
I was like this too, hating on the classes. But they are actually powerful if you are willing to learn how to use them properly
@producdevity
Жыл бұрын
What are classes?
@Noam-Bahar
11 ай бұрын
I use interfaces for typing React component props, since I can extend the base HTML element props
@petarkolev6928 Жыл бұрын
Amazing deep dive into something that one would never even thing of existing in the first place! Bravo, Matt 🍻
@nbspnbspnbsp Жыл бұрын
Loved hearing your journey with this decision! It was very relatable, because I feel like I flip flop like this with everything in my life, not just technology...😅
@amin001001 Жыл бұрын
Man, this video just put an end to all the madness I've been through. Thank you very very much.
@Svengtz Жыл бұрын
This is 100% my philosophy for interacting with types and interfaces. Awesome Video!
@ThaRealIansanity Жыл бұрын
I'm a noob so of course at first (last week), I was using interfaces for anything and everything more than a one line type definition. I've been coming around to your way of thinking more over the past few days and I feel better after hearing what you have to say about it. Thanks
@snk-js Жыл бұрын
this video is very instructive for someone that doesn't went deep into types but still appreciate how is the common sense related to this way of typing things
@arakwar Жыл бұрын
I also went back and forth between both for a while, but ultimately settled for something like you did. Use types when I need their features, use interfaces when I need their features. And, if I absolutely don’t need any of their features, that actually raise the question why and we try to figure out if we truly need that new type/interface in the way we see it. Oftentimes we realise that processing an existing type trough a generic or a mapped type.
@devanfarrell16 Жыл бұрын
Love it. Been using exclusively types for awhile mostly because of the consistency. Had no idea that interfaces even had these issues.
@GiovanniRavalico Жыл бұрын
Small note: `types` unwraps to the underlying structures, `interfaces` preserve the "box" name throughout
@karmasakshi
Жыл бұрын
I’d like to understand your comment better. Can you give an example please?
@dealloc
Жыл бұрын
@@karmasakshi What he means is that type hints are not expanded when using interfaces. Although they are also not expanded when you intersect or union types together: interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } type ExampleInterface: SomeInterface; // => SomeInterface (not expanded) type A = { a: number }; type B = { b: string }; type SomeIntersection = A & B; // => A & B (not expanded) To get around this you can convert interface into a type, as well as simplify the intersection types by looping over them to combine them: type Simplify = { [K in keyof T]: T[K] }; type SimplifiedInterface: Simplify = literal; // => { foo: number, bar?: string; baz: number | undefined; } const SimplfiedIntersection: Simplify { a: number, b: string };
@antoninoadornetto6958 Жыл бұрын
This is just what I was looking for! Thank you
@Alpheus24 ай бұрын
Appreciate the candor, Matt!
@vinhtrinh9662 Жыл бұрын
first time viewer. good content and also pleasant to watch. Thank you
@realitydesigners Жыл бұрын
Thank you! Wanted to know more about this and you explained it well! 🎉
Жыл бұрын
I use interfaces only in a 'classic' OO sense: describe abstractions which multiple classes can inherit and provide the functionality described by the interface. These are usually 'classic' OO objects with private data, getters/setter and member functions ... no 'weird' JS stuff :). For all other purposes I find types to be superior (mainly due to discriminating unions). I also find describing a function via interface weird personally so I would always do it via type alias.
@imagineabout4153
Жыл бұрын
Same here!
@romfrolov Жыл бұрын
Great explanation. Thank you, Matt. I've always been on the side of "use types for everything except if you want to use "class implements interface" feature. My reasoning was simply I don't have enough reasons to use interfaces for anything else.
@DemPilafian
11 ай бұрын
KISS FTW.
@Hackkit7 ай бұрын
I always did this without even thinking about it, it's awesome to know the Typescript guru also do the same.
@vinception7773 ай бұрын
Great video, thanks a lot for sharing, I really love the way you're explaining things :)
@BalaevArif Жыл бұрын
Many thanks for content and insides!
@19n1ght Жыл бұрын
There is also a difference in error handling. If you have 2 interfaces with property with the same name but different type, you will get a compile error. If you do the same with types, you will get a never type.
@shapelessed
Жыл бұрын
Which you'll later spend 15 minutes on debugging/tracking down just to find out about this small little detail you've missed... Kind of reminds me of tracking down silly typos in plain JS... Reference errors all over the place due to fast typing, and always in the exact wrong moments.
@flygonfiasco97517 ай бұрын
Typescript docs recommend to use interfaces until you need types because interfaces have more readable errors. Would love a follow up with this considered
@SuperQuwertz
3 ай бұрын
Or, they could at least implement syntax highlighting and properly formatted error messages Those issues are stale for over a year now lol
@shinodinhaa Жыл бұрын
For me is weird using types for everything because I always though interfaces are the entrypoints for connecting things, the shape of the IO of a thing, and types were entities. But I always ended up using types to avoid the augmentation, because that is tricky to visualize and handle sometimes (at least for me).
@nabinsaud4688 Жыл бұрын
TypeScript hero ❤️ .Thankyou so much legend
@priyank882 ай бұрын
Great piece of advice !!!
@jd4codes Жыл бұрын
Excellent video!
@user-rb8lu6cn8r8 ай бұрын
very good clarification thank you
@nickchauhan Жыл бұрын
Thanks Matt!
@andy_lamax Жыл бұрын
I personally use interfaces for everything unless I need types (Intersections, Unions, Type aliases, inferences, e.t.c)
@MarekFodor
Жыл бұрын
Same here.
@FurryDanOriginal
5 ай бұрын
Same here. While I do think it's very important to be consistent in your codebase, I will not prefer types over interfaces simply because they're more powerful as I see them convey 2 different ideas. Types are just shorthands for whatever you define them to be and interfaces define a forced / non-dynamic structure for an object. Therefore I use them as such.
@user-tc2oi7ii9s10 ай бұрын
This was my approach for quite some time, the risk of working with types is when you extend an object. with type you can override any property of the extended object, while interface will not let you do this, so I'm using interface unless I know I want to override one of the extended object properties (or do something else that only type can do)
@enfieldli9296 Жыл бұрын
Ok, now thanks to you, I'll have to convert all my interfaces to types again. Kiding 😄, good stuff!
@drjones694 Жыл бұрын
I'm so glad you made this I ran into this last year and kinda used both in the same project I couldn't figure out what then difference was But... Everywhere you look says use an interface Now I get it use Types in JavaScript / react the majority of times for safety reasons Then use interfaces pretty much in every other language 😮😊
@willmarsh964 Жыл бұрын
types work better with Visual Studio intellisense so when you hover over something that has a type it shows you the type definition, whereas with an interface you have to navigate to the interface to see it’s definition
@cat-.-
Жыл бұрын
Because typs is just an alias and interface is ….. whatever i dont even onow
@jeromesnail
Жыл бұрын
This. I hate to only see the name when I'm hover a type name and it just gives me. I'm mean, thanks captain 🙄
@benhaynes8869
Жыл бұрын
if you hold `command` (mac) or `ctrl` (windows) before you hover it will show you the interface definition
@AngelHdzMultimedia
Жыл бұрын
I just found out that if we hover over the type itself, yes we get the whole type definition, but if we hover over the variable defined with the type, it just shows the name of the type, unless we press Ctrl before hovering. I learned this shortcut from @Ben Haynes in this comment! Thanks!
@harleyspeedthrust40134 ай бұрын
phase 3 is where it's at, imo you should default to types and use interfaces when you have a specific need for them. note also that a class can implement a `type`, and sometimes you want to do this - in my experience you usually want an interface when doing classical OOP (i.e. not implementing arbitrary types) or when augmenting a module to merge an interface declaration. it's also worth noting that all object types (whether declared via `type`, `interface`, or inline) are open to extension, meaning that they can always contain extra properties that are not declared on the type. this is a feature of the language and it's the reason why Object.hasOwnProperty doesn't return a type predicate and Object.keys doesn't have a narrower return type.
@mdevelop_10 ай бұрын
I'm also using the 3rd option and it's probably best practice how using types in typescript but for typing API json objects i'm also using interfaces.
@Igor_Lemes Жыл бұрын
Thanks for the video! I’ve been searching about types x interfaces for a quite but you were the first who actually pointed a real use case of both. That being said, is there a “semantic” (in terms of good practices or convention)use case for types/interfaces apart from its inner functionalities?
@maksymbaranovskyi8362
Жыл бұрын
In objecty-oriented languages interfaces are meant to be used to describe what a certain thing (class) can do. It doesn't describe structure but behavior. Thus, using it to describe fields in the object is not a good practice - types suit it better.
@imjeffreylee Жыл бұрын
i like your conclusion
@9SMTM6 Жыл бұрын
I've almost exclusively used Types for a looong time. Yeah I've used interfaces indirectly and also in the VERY seldom situation where I needed to eg extend a global interface, but otherwise it's all been types. And for my part a type union is what interface extension should always have been, and with its connected operations is just better. The ONE thing where I sometimes miss interfaces is that they can be self-referential, and most of the times that probably should be avoided anyways. But if you've got an interface that has a few fields that use similar types or something like that, you can use this.field to refer to the type of 'field'. That probably is possible due to the same mechanic as interface extension now that I think about it. Anyways, that has been somewhat fascinating for me. But it's not neccesarily all that predictable and in many instances you'll find other ways to express that stuff that are just a bit more usual and predictable.
@MiSt3300 Жыл бұрын
Yes, haha I love the word interface, and that's why I use interfaces over types. Thanks for your video though, I wasn't even aware of these differences between them
@hectorluisbarrientosmargol9303 Жыл бұрын
I just found this amazing blog, so happy with its valuable content. I was wondering would u mind to prepare one about Hexagonal(Dependency Inversion) in TS? I come from OOP and I find TS really powerful but at times I miss the stability that brings Hexagonal and Service contracts in the form of Interfaces
@jozsefsebestyen8228 Жыл бұрын
Module augmentation can be used or abused. Good example is MUI Material library, where you can extend a component's prop interface without the need of reexporting the component or the interface, so you can use those props in styling
@levantos Жыл бұрын
This has been my approach for the last 2 years, only use Interfaces when you need them specifically for one of their unique features. Beforehand I was captain interface for everything! 😂
@xbsidesx Жыл бұрын
Yup, that’s what I thought and use for years. Thanks for the video though!
@matthewbevis2838 Жыл бұрын
Thank goodness! :)
@TreeLuvBurdpuАй бұрын
I changed my mind three times just watching this video.
@benlu Жыл бұрын
There's a canonical blog post on this 5 years ago. Good to see that advice hasn't changed
@cyberuni Жыл бұрын
One thing that interface is better than type (arguably) is when you want to hide the complexity of the types in IDE. type is type alias and they will expand by default when you hover over the variable (in normal cases, there are exceptions). for interface, it will show the name of the interface only. It's a "it depends" case really, because in function arguments, types is typically better because you can see what you need inside the variable. On the other hand, when reading a variable interface can be cleaner. However, I still stick with what I recommend. Use type over interface.
@dealloc
Жыл бұрын
One could argue that it's desired to simplify the type because it improves type hints, which otherwise would require you to poke into the type before you know its shape. One problem you can end up in when using interfaces, though, is when you try to pass a value that is an interface type into an wider type, i.e. a Record in a function argument, even though they may have identical shapes: interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } const literal = {foo: 123, bar: 'hello', baz: 456}; const someInterface: SomeInterface = literal; function fn(object: Record): void {} fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened To get around this you can simplify the type by converting the interface to a type: type Simplify = { [K in keyof T]: T[K] }; fn(someInterface as Simplify); // Transform an `interface` into a `type`, resulting in hapiness On top of this is can be used to simplify the types for intersection and union types, which would otherwise also hide the shape: type A = { a: number }; type B = { b: string }; type AB = A & B; // => A & B type ABSimplified = Simplify // => { a: number, b: string }
@lostinchina8585
Жыл бұрын
This is exactly why we use types over interfaces
@alexbcn7710 ай бұрын
good point!
@whosdr11 ай бұрын
I've had some niche little quirks where using an object intersection would break a type guard function, but rewriting those same types as interfaces with inheritance worked just fine. I have no idea why it behaved that way, but interfaces fixed it so those will forever be interfaces.
@AntonioBrandao3 ай бұрын
Nailed it.
@tino3420 Жыл бұрын
I started to use types more when I found out that the tooltips on vs code for types are much better.
@yaakovbennett
Жыл бұрын
Haha you just convinced me
@jzmmm8 ай бұрын
I use Type only. I used to use interfaces because I came from c#. But types as you said are predictable and just work nicely.
@a_maxed_out_handle_of_30_chars8 ай бұрын
thank you :)
@Gruby7C1h Жыл бұрын
So far I've only once had to use an interface... Types, and especially unions, are my favorite thing about TS.
@joestevenson5568 Жыл бұрын
"If you want something predictable that's never going to act strange or do wierd things in certain situation then use types" I'm going to counter that by saying that if you don't want wierd and strange behaviour then avoid Javascript entirely lol.
@DemPilafian11 ай бұрын
I was having an anxiety attack waiting for the final answer and just praying that it was *types.* Phew, I can breathe easier now.
@json_bourne3812 Жыл бұрын
If anything the example given at the end makes me appreciate interfaces more, since to me it points out the flaw in the example. If I already know the data's structure well enough to be typing it (such as MyData in the example), then I'm more likely just going to modify the JSONValue type and the handle function to be generics that can take which exact set of keys I'll be expecting rather than just "[key: string]" to get better type-safety. If you only need the function to handle those 4 options then you don't even run into the problem. Personally and the main reason I 100% prefer interfaces is I think interfaces visually are much cleaner, and even eye-catching in comparison to the rest of the code. "type FooBar = {}" and "const fooBar = {}" are SOOOO similar, that it visually homogenises the code just that tiiiiny bit more than I'd like. Taking that one step further, extending interfaces is also more visually distinct and IMO less cluttery than "&" characters slotted between types. Even separating those concerns into their own files can sometimes create a different type of problem where if you're moving very quickly through your code (jumping through go-tos, cursor back-forths) that when everything has the same structure and (depending on your editor) the same colours you can't identify certain things as quickly. In the end mainly due to the very particular and petty reasons above I'm in the "use whatever!" camp. Unless you have some very specific use-cases, then using whatever is perfectly fine!
@user-ul8qv2so7g Жыл бұрын
so many beautiful things to do in life and you decided to benchmark thousands of types with interfaces
@mattpocockuk
Жыл бұрын
I've wasted my precious hours
@user-ul8qv2so7g
Жыл бұрын
@@mattpocockuk just kidding bro, thanks a lot :) was helpful
@marcusrehn6915 Жыл бұрын
I have always preferred types because of the intersections.
@gasparsigma11 ай бұрын
I share your phase 3 view. I only use interfaces in very specific cases and types as default
@kaidenrogers Жыл бұрын
I like that you said "If you like the word interface, use interface". More people should acknowledge your preference when giving advice.
@und0 Жыл бұрын
I tend to rarely use interfaces even though the extension syntax for interfaces is a bit cleaner, I usually just use the intersection operator. I've resolved to only use interfaces for implementing classes which I rarely do because I don't write a lot of classes (oop is the devil (class is still a good tool, just don't orient your entire program with them)).
@TheRishikesh99 Жыл бұрын
I assume interfaces getting merged can be useful in places where npm packages can extend functionality for some lib without re publishing the original lib, as some sort of plugin system that can be made a bit more broadly version compatible.
@fishfpv9916 Жыл бұрын
BTW you can extend a type in a class definition
@emilemil1 Жыл бұрын
I use types for most things because they are strict, which tends to keep objects cleaner and enables many useful utility functions that rely on knowing exactly which properties exist and don't exist on an object. Interfaces are best used when you explicitly don't want control over the properties of an object. If it doesn't matter I'll default to types.
@doniaelfouly4142 Жыл бұрын
Thanks
@mpowereer6992 Жыл бұрын
When your course will be available?
@brucewayne2480 Жыл бұрын
This is why I use types type x = { firstName: string} And if I change my mind to do type x = string Only types can do that Plus the type utilities that I use a lot
@yuriygerasimovich4187 Жыл бұрын
Does this discussion with the Typescript team happened to be somewhere on the GitHub or it was private? Asking because it would be interesting to read the whole thread
@jii808 Жыл бұрын
Matt, what are your thoughts on organizing types and interfaces in a project and naming? Separate /types and /interfaces folders? What about file naming? use name.ts or name.interface.ts / name.type.ts?
@mattpocockuk
Жыл бұрын
types.ts
@lamspam
Жыл бұрын
Jon, please don't put all your types in a single file (unless they can all fit on the screen without scrolling while in an editor). that's a bad practice and terrible to see in enterprise code regarding folders and naming, it really depends on the project, how many files there are, and the team - if they're models, just put them in a /models folder like `/models/name.ts` - if the models folder grows to like 10+ files, then consider reorganizing the files
@winter_light Жыл бұрын
Could you please share the details of the lamp in the background?
@AmodeusR Жыл бұрын
I generally end up using types for functional programming and interfaces for OOP. Or is it also better to use types when using classes?
@eleah2665 Жыл бұрын
Hello and thanks.
@stefankyriacou7151 Жыл бұрын
I agree with your statements in this video, though i'd probably add, I usually use interfaces more if i'm using es6 class syntax, because they just generally go well together feature wise.
@re.liable Жыл бұрын
I'm new to TS. Went with `type` as a default because it looks closer to vanilla JS than interfaces.
@malvoliosf Жыл бұрын
Welcome to the party, pal.
@ShaharHarshuv Жыл бұрын
Types "intersections" is exactly the same as interface inheritance. The only things interfaces can do and types can't is declaration merging.
@ShaharHarshuv
Жыл бұрын
You can even "implement" a type in a class. Which really makes interfaces redundant.
@Metruzanca Жыл бұрын
Seems we both came to the same conclusion. I used to use interfaces but I ran into werid instances where types just worked better and now I use types for everything unless I need a specific feature of interfaces.
@jgkdmdevienjjgg8866 Жыл бұрын
My thought is that types should be preferred unless you need to do abstraction/contract where you could have potentially multiple implementations of the same contract. Caring about performance is bad for code readability here. Even if it does differ. We trade readability for runtime performance even... type is just keyword for any TYPE. if we had normal complex runtime types in js, there would be no such thing as declaring specific object shape type and using it as contract for something. That would be just abstract class type of things (from oop world). Interfaces is more semantic thing than technical. It means abstract stuff out. In c++ they even do keyword redifinition, so class and interface is completely same thing. Differs only on semantic level, on technical side it's just pure abstract class. From this perspective i prefer types for declaring props in react, yes it's objects all the time, but they are not abstractions - they are concrete specific types (it's more like DTO objects for passing arguments)
@Ostap1974 Жыл бұрын
I prefer to choose interface for anything that can be thought as abstact API to an object and types for anything else.
@mpowereer6992 Жыл бұрын
i use interfaces for objects/component props and types for anything else
@karamuto1565 Жыл бұрын
We actually used to use abstract classes instead of interfaces in Typescript as they can also just be implemented and don't have this. Well we also didn't use much experience with Typescript overall that point and today I would scrap that idea.
@Bunnokazooie Жыл бұрын
I use types because they work with the type union operator.
@andrewdunbar8282 ай бұрын
I need to assignate myself the task of looking into the difference between assignment and assignation.
@mattpocockuk
2 ай бұрын
Assignate isn't a word, for starters
@stanislauyan3204 Жыл бұрын
Used to use interfaces all the time, but few months ago moved to types, because they do not merge each other. And backend data are better with types. You cannot reuse the same name and Union of types are better to work with.
@grgry06 Жыл бұрын
Though I want to match my own flavor, since interfaces look fancier than types, I might reconsider using types than interfaces.
@mrgerbeck Жыл бұрын
Overloading interfaces with function IO seems to preserve types better than alternative methods. At least where enums are used.
@RedStone576 Жыл бұрын
interface just sounds oo and just has a better vibes
@zsytssk5176 Жыл бұрын
Type has four character, Interfaces has 10 character. what a obvoius choice! Type is always my first choice. I use interface when you cant use type. In my expirence in typescript I havnt encounter that situation.
@niner827511 ай бұрын
Hm, never thought so much about it, but I never considered one to be better or worse in general. Just like in your conclusion, I use what's best suited for the purpose. Besides that, the very frequent zooming makes me a bit seasick, but I am also old ;-)
@snatvb Жыл бұрын
I promote using types instead of interfaces to describe Props in React just because of merging, Props types are finite, like saled classes in other languages Performance suffers only if they are complex, interfaces are cached, types are not
@juliusbagdonas3136 Жыл бұрын
Also, it's called typescript, not interfacescript. Just saying...
@spencersablan8765 Жыл бұрын
I’m in the “I like the word interface” category
@rubenheymans1988 Жыл бұрын
you can do something like this though: type Case = Base & { title: string; synopsis: string;
@OliverCarvajal-lf3nt9 ай бұрын
For anyone trying to dive deep into why a Type works but an interface won't, I quote one of the members of the TS teams from an issue of 2017 in this regard "this behavior is currently by design. Because interfaces can be augmented by additional declarations but type aliases can't, it's "safer" (heavy quotes on that one) to infer an implicit index signature for type aliases than for interfaces. But we'll consider doing it for interfaces as well if that seems to make sense"
@benjidaniel5595 Жыл бұрын
Another reason why I’m starting to use types by default is: interface SomeObject { someProperty: string } is not assignable to Record But the type version is: type SomeObject = { someProperty: string }
@dealloc
Жыл бұрын
Indeed. It's very annoying. But if you for some reason have to consume an interface, you can convert it into a type by simplifying it: type Simplify = { [K in keyof T]: T[K] }; function fn(object: Record): void {} fn(someInterface as Simplified); // Now this works!
@ayehavgunne10 ай бұрын
You should do that "it doesn't matter man" accent all the time.
@DrWarpMan Жыл бұрын
Does it really matter for an irrelevant TypeScript "newbie" such as myself? I simply use interface for objects, and type for anything else. That's it, no other logic behind it, and I don't think someone like me even needs any logic to it.
@mattpocockuk
Жыл бұрын
If I were teaching someone from scratch, I'd recommend they use types for everything until they need interfaces. I think the traditional framing of interfaces being the default isn't correct - you just won't need most features of interfaces.
Пікірлер: 277
Finally someone actually highlighted that Interfaces have different features from types. Good bless this man.
@Issvor
Жыл бұрын
I'm just learning TS and pretty much most basic tutorials or articles I've found just say "types and interfaces do the same thing", so this video definitely caught me by surprise
@benjidaniel5595
Жыл бұрын
Interfaces really only have 1 feature, interface merging. Types can do everything else and much more
@kentlarsson1263
Жыл бұрын
I think its varied a lot over the development of Typescript what they can do, which probably adds to the confusion. Personally I think it was a mistake in the language design to have two things for this.
@BrunoOliveira-lm6wl
Жыл бұрын
@@benjidaniel5595 Not only 1, but they also handle conflicts much sooner than what you would get with types. But as a general rule I use types most of the time, I like to think of types with unions and intersections much more than with interfaces.
@treyrader
3 ай бұрын
Bytegrad does too sorta. Mostly he just discusses how to achieve the same results though. His take away is that it's best to be consistent so chose one vs the other. Gets interesting when you use shadcn though since all of its boilerplate is extended with interface
This is my preferred approach. Use types by default, and interfaces only when necessary. I find type intersections and unions to be very useful
@happyfase
Жыл бұрын
But when is it necessary?
@JeyPeyy
Жыл бұрын
@@happyfase I think when you need to extend global types, such as the Window type. Or extending a library (or creating a library which should be possible to extend) I suppose.
@DemanaJaire
Жыл бұрын
@@happyfase Tell me you haven't watched the video without telling me that you haven't watched the video.
@vukkulvar9769
Жыл бұрын
I find interfaces to be much cleaner when reading errors. Especially when there is a lot of properties.
@davidstephen7070
Жыл бұрын
@@happyfase use interface if you think the implementation type will have multiple version. Like general type animal thing. Like walk, fly and swim. Walk speed each animal can be differend. not all animal can fly. not all animal can swim too deep.
When the video is the normal distribution meme with the newbie and the guru saying "use types by default" btw great content as always, love that you took on this journalistic effort, it's perfect to keep the pulse on TS world. Thank you!
I use interfaces for classes and types for everything else... so yeah, I never use interfaces 😉
@alichamas63
Жыл бұрын
Well that's just lovely
@imagineabout4153
Жыл бұрын
I was like this too, hating on the classes. But they are actually powerful if you are willing to learn how to use them properly
@producdevity
Жыл бұрын
What are classes?
@Noam-Bahar
11 ай бұрын
I use interfaces for typing React component props, since I can extend the base HTML element props
Amazing deep dive into something that one would never even thing of existing in the first place! Bravo, Matt 🍻
Loved hearing your journey with this decision! It was very relatable, because I feel like I flip flop like this with everything in my life, not just technology...😅
Man, this video just put an end to all the madness I've been through. Thank you very very much.
This is 100% my philosophy for interacting with types and interfaces. Awesome Video!
I'm a noob so of course at first (last week), I was using interfaces for anything and everything more than a one line type definition. I've been coming around to your way of thinking more over the past few days and I feel better after hearing what you have to say about it. Thanks
this video is very instructive for someone that doesn't went deep into types but still appreciate how is the common sense related to this way of typing things
I also went back and forth between both for a while, but ultimately settled for something like you did. Use types when I need their features, use interfaces when I need their features. And, if I absolutely don’t need any of their features, that actually raise the question why and we try to figure out if we truly need that new type/interface in the way we see it. Oftentimes we realise that processing an existing type trough a generic or a mapped type.
Love it. Been using exclusively types for awhile mostly because of the consistency. Had no idea that interfaces even had these issues.
Small note: `types` unwraps to the underlying structures, `interfaces` preserve the "box" name throughout
@karmasakshi
Жыл бұрын
I’d like to understand your comment better. Can you give an example please?
@dealloc
Жыл бұрын
@@karmasakshi What he means is that type hints are not expanded when using interfaces. Although they are also not expanded when you intersect or union types together: interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } type ExampleInterface: SomeInterface; // => SomeInterface (not expanded) type A = { a: number }; type B = { b: string }; type SomeIntersection = A & B; // => A & B (not expanded) To get around this you can convert interface into a type, as well as simplify the intersection types by looping over them to combine them: type Simplify = { [K in keyof T]: T[K] }; type SimplifiedInterface: Simplify = literal; // => { foo: number, bar?: string; baz: number | undefined; } const SimplfiedIntersection: Simplify { a: number, b: string };
This is just what I was looking for! Thank you
Appreciate the candor, Matt!
first time viewer. good content and also pleasant to watch. Thank you
Thank you! Wanted to know more about this and you explained it well! 🎉
I use interfaces only in a 'classic' OO sense: describe abstractions which multiple classes can inherit and provide the functionality described by the interface. These are usually 'classic' OO objects with private data, getters/setter and member functions ... no 'weird' JS stuff :). For all other purposes I find types to be superior (mainly due to discriminating unions). I also find describing a function via interface weird personally so I would always do it via type alias.
@imagineabout4153
Жыл бұрын
Same here!
Great explanation. Thank you, Matt. I've always been on the side of "use types for everything except if you want to use "class implements interface" feature. My reasoning was simply I don't have enough reasons to use interfaces for anything else.
@DemPilafian
11 ай бұрын
KISS FTW.
I always did this without even thinking about it, it's awesome to know the Typescript guru also do the same.
Great video, thanks a lot for sharing, I really love the way you're explaining things :)
Many thanks for content and insides!
There is also a difference in error handling. If you have 2 interfaces with property with the same name but different type, you will get a compile error. If you do the same with types, you will get a never type.
@shapelessed
Жыл бұрын
Which you'll later spend 15 minutes on debugging/tracking down just to find out about this small little detail you've missed... Kind of reminds me of tracking down silly typos in plain JS... Reference errors all over the place due to fast typing, and always in the exact wrong moments.
Typescript docs recommend to use interfaces until you need types because interfaces have more readable errors. Would love a follow up with this considered
@SuperQuwertz
3 ай бұрын
Or, they could at least implement syntax highlighting and properly formatted error messages Those issues are stale for over a year now lol
For me is weird using types for everything because I always though interfaces are the entrypoints for connecting things, the shape of the IO of a thing, and types were entities. But I always ended up using types to avoid the augmentation, because that is tricky to visualize and handle sometimes (at least for me).
TypeScript hero ❤️ .Thankyou so much legend
Great piece of advice !!!
Excellent video!
very good clarification thank you
Thanks Matt!
I personally use interfaces for everything unless I need types (Intersections, Unions, Type aliases, inferences, e.t.c)
@MarekFodor
Жыл бұрын
Same here.
@FurryDanOriginal
5 ай бұрын
Same here. While I do think it's very important to be consistent in your codebase, I will not prefer types over interfaces simply because they're more powerful as I see them convey 2 different ideas. Types are just shorthands for whatever you define them to be and interfaces define a forced / non-dynamic structure for an object. Therefore I use them as such.
This was my approach for quite some time, the risk of working with types is when you extend an object. with type you can override any property of the extended object, while interface will not let you do this, so I'm using interface unless I know I want to override one of the extended object properties (or do something else that only type can do)
Ok, now thanks to you, I'll have to convert all my interfaces to types again. Kiding 😄, good stuff!
I'm so glad you made this I ran into this last year and kinda used both in the same project I couldn't figure out what then difference was But... Everywhere you look says use an interface Now I get it use Types in JavaScript / react the majority of times for safety reasons Then use interfaces pretty much in every other language 😮😊
types work better with Visual Studio intellisense so when you hover over something that has a type it shows you the type definition, whereas with an interface you have to navigate to the interface to see it’s definition
@cat-.-
Жыл бұрын
Because typs is just an alias and interface is ….. whatever i dont even onow
@jeromesnail
Жыл бұрын
This. I hate to only see the name when I'm hover a type name and it just gives me. I'm mean, thanks captain 🙄
@benhaynes8869
Жыл бұрын
if you hold `command` (mac) or `ctrl` (windows) before you hover it will show you the interface definition
@AngelHdzMultimedia
Жыл бұрын
I just found out that if we hover over the type itself, yes we get the whole type definition, but if we hover over the variable defined with the type, it just shows the name of the type, unless we press Ctrl before hovering. I learned this shortcut from @Ben Haynes in this comment! Thanks!
phase 3 is where it's at, imo you should default to types and use interfaces when you have a specific need for them. note also that a class can implement a `type`, and sometimes you want to do this - in my experience you usually want an interface when doing classical OOP (i.e. not implementing arbitrary types) or when augmenting a module to merge an interface declaration. it's also worth noting that all object types (whether declared via `type`, `interface`, or inline) are open to extension, meaning that they can always contain extra properties that are not declared on the type. this is a feature of the language and it's the reason why Object.hasOwnProperty doesn't return a type predicate and Object.keys doesn't have a narrower return type.
I'm also using the 3rd option and it's probably best practice how using types in typescript but for typing API json objects i'm also using interfaces.
Thanks for the video! I’ve been searching about types x interfaces for a quite but you were the first who actually pointed a real use case of both. That being said, is there a “semantic” (in terms of good practices or convention)use case for types/interfaces apart from its inner functionalities?
@maksymbaranovskyi8362
Жыл бұрын
In objecty-oriented languages interfaces are meant to be used to describe what a certain thing (class) can do. It doesn't describe structure but behavior. Thus, using it to describe fields in the object is not a good practice - types suit it better.
i like your conclusion
I've almost exclusively used Types for a looong time. Yeah I've used interfaces indirectly and also in the VERY seldom situation where I needed to eg extend a global interface, but otherwise it's all been types. And for my part a type union is what interface extension should always have been, and with its connected operations is just better. The ONE thing where I sometimes miss interfaces is that they can be self-referential, and most of the times that probably should be avoided anyways. But if you've got an interface that has a few fields that use similar types or something like that, you can use this.field to refer to the type of 'field'. That probably is possible due to the same mechanic as interface extension now that I think about it. Anyways, that has been somewhat fascinating for me. But it's not neccesarily all that predictable and in many instances you'll find other ways to express that stuff that are just a bit more usual and predictable.
Yes, haha I love the word interface, and that's why I use interfaces over types. Thanks for your video though, I wasn't even aware of these differences between them
I just found this amazing blog, so happy with its valuable content. I was wondering would u mind to prepare one about Hexagonal(Dependency Inversion) in TS? I come from OOP and I find TS really powerful but at times I miss the stability that brings Hexagonal and Service contracts in the form of Interfaces
Module augmentation can be used or abused. Good example is MUI Material library, where you can extend a component's prop interface without the need of reexporting the component or the interface, so you can use those props in styling
This has been my approach for the last 2 years, only use Interfaces when you need them specifically for one of their unique features. Beforehand I was captain interface for everything! 😂
Yup, that’s what I thought and use for years. Thanks for the video though!
Thank goodness! :)
I changed my mind three times just watching this video.
There's a canonical blog post on this 5 years ago. Good to see that advice hasn't changed
One thing that interface is better than type (arguably) is when you want to hide the complexity of the types in IDE. type is type alias and they will expand by default when you hover over the variable (in normal cases, there are exceptions). for interface, it will show the name of the interface only. It's a "it depends" case really, because in function arguments, types is typically better because you can see what you need inside the variable. On the other hand, when reading a variable interface can be cleaner. However, I still stick with what I recommend. Use type over interface.
@dealloc
Жыл бұрын
One could argue that it's desired to simplify the type because it improves type hints, which otherwise would require you to poke into the type before you know its shape. One problem you can end up in when using interfaces, though, is when you try to pass a value that is an interface type into an wider type, i.e. a Record in a function argument, even though they may have identical shapes: interface SomeInterface { foo: number; bar?: string; baz: number | undefined; } const literal = {foo: 123, bar: 'hello', baz: 456}; const someInterface: SomeInterface = literal; function fn(object: Record): void {} fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened To get around this you can simplify the type by converting the interface to a type: type Simplify = { [K in keyof T]: T[K] }; fn(someInterface as Simplify); // Transform an `interface` into a `type`, resulting in hapiness On top of this is can be used to simplify the types for intersection and union types, which would otherwise also hide the shape: type A = { a: number }; type B = { b: string }; type AB = A & B; // => A & B type ABSimplified = Simplify // => { a: number, b: string }
@lostinchina8585
Жыл бұрын
This is exactly why we use types over interfaces
good point!
I've had some niche little quirks where using an object intersection would break a type guard function, but rewriting those same types as interfaces with inheritance worked just fine. I have no idea why it behaved that way, but interfaces fixed it so those will forever be interfaces.
Nailed it.
I started to use types more when I found out that the tooltips on vs code for types are much better.
@yaakovbennett
Жыл бұрын
Haha you just convinced me
I use Type only. I used to use interfaces because I came from c#. But types as you said are predictable and just work nicely.
thank you :)
So far I've only once had to use an interface... Types, and especially unions, are my favorite thing about TS.
"If you want something predictable that's never going to act strange or do wierd things in certain situation then use types" I'm going to counter that by saying that if you don't want wierd and strange behaviour then avoid Javascript entirely lol.
I was having an anxiety attack waiting for the final answer and just praying that it was *types.* Phew, I can breathe easier now.
If anything the example given at the end makes me appreciate interfaces more, since to me it points out the flaw in the example. If I already know the data's structure well enough to be typing it (such as MyData in the example), then I'm more likely just going to modify the JSONValue type and the handle function to be generics that can take which exact set of keys I'll be expecting rather than just "[key: string]" to get better type-safety. If you only need the function to handle those 4 options then you don't even run into the problem. Personally and the main reason I 100% prefer interfaces is I think interfaces visually are much cleaner, and even eye-catching in comparison to the rest of the code. "type FooBar = {}" and "const fooBar = {}" are SOOOO similar, that it visually homogenises the code just that tiiiiny bit more than I'd like. Taking that one step further, extending interfaces is also more visually distinct and IMO less cluttery than "&" characters slotted between types. Even separating those concerns into their own files can sometimes create a different type of problem where if you're moving very quickly through your code (jumping through go-tos, cursor back-forths) that when everything has the same structure and (depending on your editor) the same colours you can't identify certain things as quickly. In the end mainly due to the very particular and petty reasons above I'm in the "use whatever!" camp. Unless you have some very specific use-cases, then using whatever is perfectly fine!
so many beautiful things to do in life and you decided to benchmark thousands of types with interfaces
@mattpocockuk
Жыл бұрын
I've wasted my precious hours
@user-ul8qv2so7g
Жыл бұрын
@@mattpocockuk just kidding bro, thanks a lot :) was helpful
I have always preferred types because of the intersections.
I share your phase 3 view. I only use interfaces in very specific cases and types as default
I like that you said "If you like the word interface, use interface". More people should acknowledge your preference when giving advice.
I tend to rarely use interfaces even though the extension syntax for interfaces is a bit cleaner, I usually just use the intersection operator. I've resolved to only use interfaces for implementing classes which I rarely do because I don't write a lot of classes (oop is the devil (class is still a good tool, just don't orient your entire program with them)).
I assume interfaces getting merged can be useful in places where npm packages can extend functionality for some lib without re publishing the original lib, as some sort of plugin system that can be made a bit more broadly version compatible.
BTW you can extend a type in a class definition
I use types for most things because they are strict, which tends to keep objects cleaner and enables many useful utility functions that rely on knowing exactly which properties exist and don't exist on an object. Interfaces are best used when you explicitly don't want control over the properties of an object. If it doesn't matter I'll default to types.
Thanks
When your course will be available?
This is why I use types type x = { firstName: string} And if I change my mind to do type x = string Only types can do that Plus the type utilities that I use a lot
Does this discussion with the Typescript team happened to be somewhere on the GitHub or it was private? Asking because it would be interesting to read the whole thread
Matt, what are your thoughts on organizing types and interfaces in a project and naming? Separate /types and /interfaces folders? What about file naming? use name.ts or name.interface.ts / name.type.ts?
@mattpocockuk
Жыл бұрын
types.ts
@lamspam
Жыл бұрын
Jon, please don't put all your types in a single file (unless they can all fit on the screen without scrolling while in an editor). that's a bad practice and terrible to see in enterprise code regarding folders and naming, it really depends on the project, how many files there are, and the team - if they're models, just put them in a /models folder like `/models/name.ts` - if the models folder grows to like 10+ files, then consider reorganizing the files
Could you please share the details of the lamp in the background?
I generally end up using types for functional programming and interfaces for OOP. Or is it also better to use types when using classes?
Hello and thanks.
I agree with your statements in this video, though i'd probably add, I usually use interfaces more if i'm using es6 class syntax, because they just generally go well together feature wise.
I'm new to TS. Went with `type` as a default because it looks closer to vanilla JS than interfaces.
Welcome to the party, pal.
Types "intersections" is exactly the same as interface inheritance. The only things interfaces can do and types can't is declaration merging.
@ShaharHarshuv
Жыл бұрын
You can even "implement" a type in a class. Which really makes interfaces redundant.
Seems we both came to the same conclusion. I used to use interfaces but I ran into werid instances where types just worked better and now I use types for everything unless I need a specific feature of interfaces.
My thought is that types should be preferred unless you need to do abstraction/contract where you could have potentially multiple implementations of the same contract. Caring about performance is bad for code readability here. Even if it does differ. We trade readability for runtime performance even... type is just keyword for any TYPE. if we had normal complex runtime types in js, there would be no such thing as declaring specific object shape type and using it as contract for something. That would be just abstract class type of things (from oop world). Interfaces is more semantic thing than technical. It means abstract stuff out. In c++ they even do keyword redifinition, so class and interface is completely same thing. Differs only on semantic level, on technical side it's just pure abstract class. From this perspective i prefer types for declaring props in react, yes it's objects all the time, but they are not abstractions - they are concrete specific types (it's more like DTO objects for passing arguments)
I prefer to choose interface for anything that can be thought as abstact API to an object and types for anything else.
i use interfaces for objects/component props and types for anything else
We actually used to use abstract classes instead of interfaces in Typescript as they can also just be implemented and don't have this. Well we also didn't use much experience with Typescript overall that point and today I would scrap that idea.
I use types because they work with the type union operator.
I need to assignate myself the task of looking into the difference between assignment and assignation.
@mattpocockuk
2 ай бұрын
Assignate isn't a word, for starters
Used to use interfaces all the time, but few months ago moved to types, because they do not merge each other. And backend data are better with types. You cannot reuse the same name and Union of types are better to work with.
Though I want to match my own flavor, since interfaces look fancier than types, I might reconsider using types than interfaces.
Overloading interfaces with function IO seems to preserve types better than alternative methods. At least where enums are used.
interface just sounds oo and just has a better vibes
Type has four character, Interfaces has 10 character. what a obvoius choice! Type is always my first choice. I use interface when you cant use type. In my expirence in typescript I havnt encounter that situation.
Hm, never thought so much about it, but I never considered one to be better or worse in general. Just like in your conclusion, I use what's best suited for the purpose. Besides that, the very frequent zooming makes me a bit seasick, but I am also old ;-)
I promote using types instead of interfaces to describe Props in React just because of merging, Props types are finite, like saled classes in other languages Performance suffers only if they are complex, interfaces are cached, types are not
Also, it's called typescript, not interfacescript. Just saying...
I’m in the “I like the word interface” category
you can do something like this though: type Case = Base & { title: string; synopsis: string;
For anyone trying to dive deep into why a Type works but an interface won't, I quote one of the members of the TS teams from an issue of 2017 in this regard "this behavior is currently by design. Because interfaces can be augmented by additional declarations but type aliases can't, it's "safer" (heavy quotes on that one) to infer an implicit index signature for type aliases than for interfaces. But we'll consider doing it for interfaces as well if that seems to make sense"
Another reason why I’m starting to use types by default is: interface SomeObject { someProperty: string } is not assignable to Record But the type version is: type SomeObject = { someProperty: string }
@dealloc
Жыл бұрын
Indeed. It's very annoying. But if you for some reason have to consume an interface, you can convert it into a type by simplifying it: type Simplify = { [K in keyof T]: T[K] }; function fn(object: Record): void {} fn(someInterface as Simplified); // Now this works!
You should do that "it doesn't matter man" accent all the time.
Does it really matter for an irrelevant TypeScript "newbie" such as myself? I simply use interface for objects, and type for anything else. That's it, no other logic behind it, and I don't think someone like me even needs any logic to it.
@mattpocockuk
Жыл бұрын
If I were teaching someone from scratch, I'd recommend they use types for everything until they need interfaces. I think the traditional framing of interfaces being the default isn't correct - you just won't need most features of interfaces.