For sure to me it all looked like code smells taking the idea of DRY too far adding more complexity then the problems they solve, or maybe a smarter way of being lazy, just write a few more lines of code and don't create un-nessisary coupling
For me its just more natural to define interface for a component rather than its type. That interface can have typed members in it self. Interface is like a contract while type defines ... well type :)
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.
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.
I've heard about following one pattern is a good practice. That means if your project uses interfaces it is right to use only interfaces and vise versa
Sure, we should try to keep consistency with the architectural patterns as well as across languages while possible. This video is a typical opinion of someone who missed the times of the transition to TS. So much multiplicity and garbage still there but, anyways, TS is the perfect example why you should never try to please everyone 😁
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.
I agree with this. You don't have to exclusively use one or the other. The bad use case examples for interfaces in this video are a result of misusing interfaces IMO.
There’s no material distinction between those two, especially in a language with function types. Maybe it’s the functional programmer in me speaking, but I try to break the boundaries between those two things and stick to the one thing that can represent EVERYTHING. However, I do understand the benefit of providing something that’s clear and similar to the code that my teammates have worked with in other languages. Just my personal preference…
@@rafaelkhan_ I agree there is no difference. However I tend to use "type" for records or structs, and interface for defining the methods that an object exposes. For example, in the Rust language, type would be the struct, and interface the trait.
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.
But you DO know things, that's unfair! here, knowledge doesn't have a place, it seems. I knew it was going to be a nope soon as a multiple-type array entered the scene
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 & {...}".
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 {}; It is just not as convenient as with types :)
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.
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
@BlueCell interface A{} interface B extends A{} //works type A = {} interface B extends A{} //works type A = {} type B = A & {} //works interface A {} type B = A & {} //breaks
The last argument pretty much makes the biggest point in favour of using 'interface', i.e. getting better error messages. When you're dealing with TypeScript and complex types that can often float around in libraries and codebases, you need all the help you can get from error messages.
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.
Interfaces can be returned to a function, which can be super helpful. Also, if interfaces are too restrictive, you can just add '[key:string]: any' to an interface and then you will be able to freely add those other props/attribute pairs you want.
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.
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.
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.
I would absolutely love a series of videos on how to get started with TypeScript, specifically the main places where TypeScript needs to be written in an app, where it doesn't, and all the necessary syntax.
I recommend using interface when dealing with objects as it provides faster performance and provides more info in code hints. If there's a need for a feature that exists only in types, then use types.
An interface not describing primitive types is _not_ a problem with interfaces... No object or class in existence implements the interface of a primitive type.... I guess what I am getting at here is that the logic underpinning your conclusions is flawed, as it does not take into account the meaning of interface. Generally speaking, my advice would be to use types unless you need the features of interfaces (eg OOP), or if you find "extends" more readable than intersection types... But definitely don't just try to "pick one" and use it for all your projects regardless of context.
I loved the "Type"Script pun. The reason I use Interfaces instead of Types is because when skimming through code Types can confuse me with regular variable assignments. But I totally agree with the video. I wished that maybe something more in between where types don't look like too much like regular code assignment but it would be as flexible as types and less verbose compare to interfaces.
Don’t use extends unless you absolutely have to because when managing a large production codebase you may eventually get stuck in a web of dependencies. Nothing is worse than sorting through a tangled web when you have a pressing deadline. Keep everything as independent and modular as possible, even if it adds a bit more boilerplate, because it will save you time in the long run.
there is one thing interface absolutely crush type, that is when building higher kinded type, an interface that can accept another utility type as argument
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.
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.
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.
Good examples for good usages of type. My pattern is to use interfaces to describe behaviour and types for state. The thing with "open interfaces" is really crap in typescript. especially when you see an interface a contract.
agree. I'm getting tired to see class defined in Typescript project: keep passing arguments to create instances do the same job, or use to create one instance only to handle a single work , instead of write curry functions. 2023 and people still stick with OOP in JS/TS development.
I disagree: I use both type & interface and as you shared in the docs, the benefit of interface is the extensibility, so you can reuse the same interface & extend it to be used in other places.Thats a big plus with complex code base where you have types manipulation to be reused in different areas of the app.
You can just use types for any of the situations you mentioned, the whole point of the video is that interfaces are the wrong primitive to use. You gonna use one when you need one, but most of the time you don't need a interface. even in large codebases.
I've had discussions about this before but never took the time to look into it properly. You've sold me with just the interface problem 1! Great video, subbed. :)
The TS compiler is more performant when extending interfaces vs. intersecting types. Usually no visual difference until you're doing something complicated and have to create a type that intersects 50-200 different object types. But if that's the case you should probably figure out why you feel the need to do so and refactor the runtime code to be more TS friendly
That doesn’t affect the production build though, right? Like, only in dev or when deploying, but the end user won’t get a performance hit because it’s already compiled.
Excellent comparison I fully agree. Thank you for sharing. I can also add one other cool feature that only can be done with types and I often use - type the object keys so no one add random stuff and get intellisense of course export type Status = | 'pending' | 'current' | 'completed' | 'skipped' export type Colors = { [key in Status]: string }
omiting something from interface, you probably did it wrong you can make the name optional property indicates that its can be null or undefined, but still there or just split the interface coz its reflecting types of different concern
Having an OOP background, imho "interface" is completely wrong in TypeScript. An interface should describe a way to communicate with other parts via methods by defining their signatures. I agree on the type is the better choice for all your examples, not because something may be ugly to write, but because it simply is wrong to me to define properties on an interface. For me, that's actually the line a draw: Types defines data structures. Interfaces define ways to communicate throughout the system.
The problem with keyword `type` is that first two letters t and y are the most hard to reach on the keyboard... the finger needs most stretch :) ... that's why I'm constantly using interfaces for object types as after two letter the completion gives me full word
9:41 Interface problem 6 Is not a problem. It is a solution. E.g. Let's say you want to add your custom environment variable typings in the process.env.d.ts or merge some global typings in global.d.ts E.g. In expressjs, if you want to add custom properties in the Request e.g. req.user and type it which is a part of the library/framework, and then you can use interface in your app code and merge the type to extend it. This is a Solution and not a problem.
Most arguments in the video and comments are mostly subjective code style. Many feel it's more natural to write interface to reason with their architecture like they did in Java and C# - I WAS in this camp and defaulted to interfaces, only using types when needed. However, there is a very frustrating error message that made me default to types: Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Since interfaces can be extended, the TypeScript team doesn't consider it safe to infer the index signature even if you provide a subset of the type (the type in question very clearly only has string indexes, so you'd except TS to naturally accept this). You often encounter this when you use generics -> POV: you made a nice generic component that should handle anything derived from your base type and when you use it TS slaps you with that error that makes no sense at first (and to me just seems like a bug!) There are two workarounds: 1) de-structuring the object before you pass it -> this is ugly and feels like a hack 2) use a type instead of an interface and inferring index signature simply works as you'd expect it
The context presented in the video seems somewhat lacking in professionalism. It's crucial to recognize that the concept of interfaces in TypeScript is deeply rooted in OOP. serving as a blueprint for OBJECTS and establishing a contract for OBJECTS. While, TypeScript's type system enables the definition of specific variable types within the system. Over the years, established development practices have fostered good habits among developers. So, implementing a class through a type alias seems akin to pushing a car by manual effort-it can be done, but the rationale behind choosing such an approach warrants thoughtful consideration. And again, interfaces provides us abstraction in OOP paradigm. This allows for separation between the interface and the actual implementation, promoting modularity and flexibility in software design. While types use idea of composition. Comments below contain good explanation. You don’t need to reinvent the bike, while it perfectly works
While it agree with you entirely on a conceptual level, the issue (problem?) with types vs. interfaces in TS specifically is how the TS engine handles them. Is this which - especially beginners - find confusing.
Address was a bad example because why create a type just for a string, just name your variable correctly. This seems redundant. The type for Address already exists, it's a string.
The most critical reason was never explained: on the same file, interfaces will not warn you if an indentifier (the name) was already used. Interfaces will simply add the fields/methods into the object. Whereas Types will warn you that the identifier is already in use.
timestamp 5:06 we can use ? operator after a particular field to makr it as optional both in interface and types so giving priority of type over interface is useless .
There are essentially no advantages other than ease of recording. This code generally looks redundant, why not just do it this way: const address: string | string[] = ['address 1', 'address 2'] Why we need create a separate type for a type that already exists???
type is for fp and interface is for oop so you can not directly think the type can substitute interface. cuz only object can have method so the interface is to make the class protocol but type is for the immunity so u cannot new an object which has state inside . the video is great but it only show us the use of the interface and type…after all thanks to the author la ❤
The hammer's problem is that it can't look at small objects; it can only drive nails, and that's its PROBLEM. On the other hand, a microscope is quite versatile. It can drive nails and examine small items. So, choose a microscope.
Great video, I'm so glad that TH-cam recommended your channel, I found myself doing a lot of mistakes that you explain in your videos and they improved my skills. Thanks!
Interfaces aims to define contract and provide definitions to the classes. The interfaces and types may look same and let you exhcnage. However, both types and interfaces have different meanings and hence different use cases!
to me interface and class were designed for people from OOP language (Java, .Net., python, Ruby, C...) switch to JS. So, I use type over all interface, because I don't want to see any classes in my Typescript project : Composition over Inheritance :).
Code should typically be open to extension and closed to modifications and I find interfaces enabling this behavior intrinsically. Interestingly since JavaScript is really loose in their definition Types tend to be a preferable construct as it mirrors this flexibility while offering observability. I tend to use Types to describe data and transient information while I lean on interfaces for classes and business logic
To keep the comparisons fair, I think we should just limit it to the things that BOTH are designed to be able to do,. In this case, it’s defining the shape of objects. Then we compare how good each is at doing those things. Otherwise it’s gonna be apples and oranges.
Interface Problem 2 is the exact reason I DON'T use Types... saying this could be an array or a string means any consumer of that data has to account for both. A type should be a single, immutable thing.
I had this conversation with my colleague and I tried to convey the differences between Interfaces and types and it wasn’t easy 😅 thanks for this thorough explanation. I also agree that using type works cleaner than interfaces
👉 NEW React & Next.js Course: bytegrad.com/courses/professional-react-nextjs
TypeScript, not InterfaceScript
Hahaha
Cool!!man
hahaha nice!
that line made me like and subscribe
😮😮😂😂😅
My rule of thumb is use interface until type is needed. 90% of the times I find myself defining objects
Samezies. Best of both worlds
For sure to me it all looked like code smells taking the idea of DRY too far adding more complexity then the problems they solve, or maybe a smarter way of being lazy, just write a few more lines of code and don't create un-nessisary coupling
yeah, i think it doesn't matter that much between type and interface
True. Same for me. Having type in all places over interfaces is bit fancy in TS though 😅
For me its just more natural to define interface for a component rather than its type. That interface can have typed members in it self. Interface is like a contract while type defines ... well type :)
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.
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.
I've heard about following one pattern is a good practice. That means if your project uses interfaces it is right to use only interfaces and vise versa
Me too. I prefer not using equal sign if i can
Sure, we should try to keep consistency with the architectural patterns as well as across languages while possible. This video is a typical opinion of someone who missed the times of the transition to TS. So much multiplicity and garbage still there but, anyways, TS is the perfect example why you should never try to please everyone 😁
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.
I agree with this. You don't have to exclusively use one or the other. The bad use case examples for interfaces in this video are a result of misusing interfaces IMO.
This is the way
There’s no material distinction between those two, especially in a language with function types. Maybe it’s the functional programmer in me speaking, but I try to break the boundaries between those two things and stick to the one thing that can represent EVERYTHING.
However, I do understand the benefit of providing something that’s clear and similar to the code that my teammates have worked with in other languages.
Just my personal preference…
@@rafaelkhan_ I agree there is no difference. However I tend to use "type" for records or structs, and interface for defining the methods that an object exposes. For example, in the Rust language, type would be the struct, and interface the trait.
Well, JS issues...
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.
But you DO know things, that's unfair! here, knowledge doesn't have a place, it seems. I knew it was going to be a nope soon as a multiple-type array entered the scene
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 & {...}".
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 {}; It is just not as convenient as with types :)
his point is that using type is just much more cleaner
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.
As a person who new on this typescript world, your video is really understandable. Thank you.
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!
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
Hmm. Didn't get you. You can do like this: `type User = IGuest & { createdAt: Date }`
@BlueCell
interface A{}
interface B extends A{} //works
type A = {}
interface B extends A{} //works
type A = {}
type B = A & {} //works
interface A {}
type B = A & {} //breaks
@tiagoc9754 you are not right. Maybe it's old version of ts? For me it works. Just tried
@@BlueCell it might be the case. I haven't tested on new versions as it never worked before
this should now work in the recent versions of TS. Maybe you mean TS interface overriding.
The last argument pretty much makes the biggest point in favour of using 'interface', i.e. getting better error messages. When you're dealing with TypeScript and complex types that can often float around in libraries and codebases, you need all the help you can get from error messages.
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.
you can use ampersand in types, it's like an extend but can do more.
One of the best of your videos which I watched. But still many to watch. Great job. Thanks.
thanks for this!! i will now stop using InterfaceScript, and use TypeScript more often! i learnt a lot, thanks!
Interfaces can be returned to a function, which can be super helpful. Also, if interfaces are too restrictive, you can just add '[key:string]: any' to an interface and then you will be able to freely add those other props/attribute pairs you want.
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.
Examples of where using type is going to break the world?
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.
This video is a great refresher of TS!
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.
Awesome vid
Thanks, appreciate it!
I would absolutely love a series of videos on how to get started with TypeScript, specifically the main places where TypeScript needs to be written in an app, where it doesn't, and all the necessary syntax.
Just finishing editing this exact video. Stay tuned :)
What do you mean where ? Everywhere !
Super, always looking to understand when to decide between these two
I recommend using interface when dealing with objects as it provides faster performance and provides more info in code hints. If there's a need for a feature that exists only in types, then use types.
An interface not describing primitive types is _not_ a problem with interfaces... No object or class in existence implements the interface of a primitive type.... I guess what I am getting at here is that the logic underpinning your conclusions is flawed, as it does not take into account the meaning of interface. Generally speaking, my advice would be to use types unless you need the features of interfaces (eg OOP), or if you find "extends" more readable than intersection types... But definitely don't just try to "pick one" and use it for all your projects regardless of context.
A bit skeptical at first but this makes sense! Thank you for sharing.
What a great video! I understand now many things what’ve not understood before! Thanks dude!
Thank you so much for your video, I just started learning typescript and it's a bit confusing at first, but I'm getting the hang of it
I loved the "Type"Script pun.
The reason I use Interfaces instead of Types is because when skimming through code Types can confuse me with regular variable assignments.
But I totally agree with the video. I wished that maybe something more in between where types don't look like too much like regular code assignment but it would be as flexible as types and less verbose compare to interfaces.
good comment
Don’t use extends unless you absolutely have to because when managing a large production codebase you may eventually get stuck in a web of dependencies. Nothing is worse than sorting through a tangled web when you have a pressing deadline. Keep everything as independent and modular as possible, even if it adds a bit more boilerplate, because it will save you time in the long run.
agreed!!
there is one thing interface absolutely crush type, that is when building higher kinded type, an interface that can accept another utility type as argument
Hmm would you mind giving an example?
@@ByteGradI assume he means generics. And yes, that is something that is extremely useful.
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.
Such an inspiring video! I’m motivated now
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.
Your voice is so smooth sounding, such a pleasure listening to you teach. Great video!
Thank you
Great summary, thank you!
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.
As someone just starting out in typescript you may have sold me on using type > interface
Good examples for good usages of type. My pattern is to use interfaces to describe behaviour and types for state.
The thing with "open interfaces" is really crap in typescript. especially when you see an interface a contract.
agree. I'm getting tired to see class defined in Typescript project: keep passing arguments to create instances do the same job, or use to create one instance only to handle a single work , instead of write curry functions. 2023 and people still stick with OOP in JS/TS development.
Funny thing is that this video convinced me to use interface over type unless necessary :)
Why?
Thats actually pretty cool
Omg, So many typescript tricks that I dont know, love it
Thanks a ton, this cleared lots of concepts...🙏
I'm going with interface always, type for everything else interface can't. So I have a nice distinction without any confusion.
super valuable video thanks mate!
I disagree:
I use both type & interface and as you shared in the docs, the benefit of interface is the extensibility, so you can reuse the same interface & extend it to be used in other places.Thats a big plus with complex code base where you have types manipulation to be reused in different areas of the app.
You can just use types for any of the situations you mentioned, the whole point of the video is that interfaces are the wrong primitive to use.
You gonna use one when you need one, but most of the time you don't need a interface. even in large codebases.
"&": Am I a joke to you
@@Enderman0000it’s like people don’t watch the video, right?… 🤦🏻♂️
Can you tell your extensions please? This auto complete of yours seems perfect! Also great video.btw
Copilot
I've had discussions about this before but never took the time to look into it properly. You've sold me with just the interface problem 1! Great video, subbed. :)
You are the best man.
I use type all the time. I can use type for anything related to type which TS needs. Typing "type" for me is faster, saving some keystrokes.
The TS compiler is more performant when extending interfaces vs. intersecting types. Usually no visual difference until you're doing something complicated and have to create a type that intersects 50-200 different object types.
But if that's the case you should probably figure out why you feel the need to do so and refactor the runtime code to be more TS friendly
That doesn’t affect the production build though, right? Like, only in dev or when deploying, but the end user won’t get a performance hit because it’s already compiled.
"more performant when extending interfaces" - may be that's why the TypeScript docs in fact recommend using interfaces over types
Excellent explained.🥰
Keep up the good work
Thank you greate video 👍👍😊😊
imo you should use interface only when you declare function, for other classes to implement
very concise and clear examples. great!
Thanks for the video. You convinced me that the type is much more useful than the interface! Like
Liked, Subscribed and Commented!!
Really appreciate your content man, very useful!
I love this sentence: "This is the typescript not interfaceScript"
Well explained! I love the TypeScript not IntefaceScript part 😂
Excellent comparison I fully agree. Thank you for sharing. I can also add one other cool feature that only can be done with types and I often use - type the object keys so no one add random stuff and get intellisense of course
export type Status =
| 'pending'
| 'current'
| 'completed'
| 'skipped'
export type Colors = {
[key in Status]: string
}
Cool
That’s pretty cool
Would argue that an enum might be a better choice though, in 95% of cases?
thanks didn't know all differences. I always use type everywhere, interface when I need it which is very weird unless when Im working with other devs
omiting something from interface, you probably did it wrong
you can make the name optional property indicates that its can be null or undefined, but still there
or just split the interface coz its reflecting types of different concern
Having an OOP background, imho "interface" is completely wrong in TypeScript. An interface should describe a way to communicate with other parts via methods by defining their signatures.
I agree on the type is the better choice for all your examples, not because something may be ugly to write, but because it simply is wrong to me to define properties on an interface. For me, that's actually the line a draw: Types defines data structures. Interfaces define ways to communicate throughout the system.
This was very helpful, thank you!
The problem with keyword `type` is that first two letters t and y are the most hard to reach on the keyboard... the finger needs most stretch :) ... that's why I'm constantly using interfaces for object types as after two letter the completion gives me full word
9:41 Interface problem 6
Is not a problem. It is a solution.
E.g. Let's say you want to add your custom environment variable typings in the process.env.d.ts or merge some global typings in global.d.ts
E.g. In expressjs, if you want to add custom properties in the Request e.g. req.user and type it which is a part of the library/framework, and then you can use interface in your app code and merge the type to extend it. This is a Solution and not a problem.
Most arguments in the video and comments are mostly subjective code style. Many feel it's more natural to write interface to reason with their architecture like they did in Java and C# - I WAS in this camp and defaulted to interfaces, only using types when needed. However, there is a very frustrating error message that made me default to types:
Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }
Since interfaces can be extended, the TypeScript team doesn't consider it safe to infer the index signature even if you provide a subset of the type (the type in question very clearly only has string indexes, so you'd except TS to naturally accept this). You often encounter this when you use generics -> POV: you made a nice generic component that should handle anything derived from your base type and when you use it TS slaps you with that error that makes no sense at first (and to me just seems like a bug!)
There are two workarounds:
1) de-structuring the object before you pass it -> this is ugly and feels like a hack
2) use a type instead of an interface and inferring index signature simply works as you'd expect it
Thank you ! It was useful
The context presented in the video seems somewhat lacking in professionalism. It's crucial to recognize that the concept of interfaces in TypeScript is deeply rooted in OOP. serving as a blueprint for OBJECTS and establishing a contract for OBJECTS. While, TypeScript's type system enables the definition of specific variable types within the system.
Over the years, established development practices have fostered good habits among developers. So, implementing a class through a type alias seems akin to pushing a car by manual effort-it can be done, but the rationale behind choosing such an approach warrants thoughtful consideration.
And again, interfaces provides us abstraction in OOP paradigm. This allows for separation between the interface and the actual implementation, promoting modularity and flexibility in software design. While types use idea of composition. Comments below contain good explanation.
You don’t need to reinvent the bike, while it perfectly works
While it agree with you entirely on a conceptual level, the issue (problem?) with types vs. interfaces in TS specifically is how the TS engine handles them. Is this which - especially beginners - find confusing.
Address was a bad example because why create a type just for a string, just name your variable correctly. This seems redundant. The type for Address already exists, it's a string.
The most critical reason was never explained: on the same file, interfaces will not warn you if an indentifier (the name) was already used.
Interfaces will simply add the fields/methods into the object. Whereas Types will warn you that the identifier is already in use.
"It's called TypeScript not InterfaceScript" :D I love your videos!
that info of double Interface declaration causing merge is helpful!
but i will still use interfaces for the sorter error message highlighting
Can you please tell us which all extensions you use ? Specifically for the intellisense. Thanks!!🙏🏼
Its actually GitHub Copilot
Crystal clear !
agree, for me interface required only if you develop some library, just because of merge availability
timestamp 5:06 we can use ? operator after a particular field to makr it as optional both in interface and types so giving priority of type over interface is useless .
So interface for objects and types for literally everything else?, very nice to know, thanks!
And type can define objects as well
I have finally understood this concept. 😋
Interface can extend String if we want it to represent primitives.
interface Address extends String {}
const address: Address = "this is an address";
Good point
There are essentially no advantages other than ease of recording.
This code generally looks redundant, why not just do it this way:
const address: string | string[] = ['address 1', 'address 2']
Why we need create a separate type for a type that already exists???
Thanks for the video, great explanation!
Really good video.
type is for fp and interface is for oop so you can not directly think the type can substitute interface. cuz only object can have method so the interface is to make the class protocol but type is for the immunity so u cannot new an object which has state inside . the video is great but it only show us the use of the interface and type…after all thanks to the author la ❤
came for the info - subbed for the voice
The hammer's problem is that it can't look at small objects; it can only drive nails, and that's its PROBLEM. On the other hand, a microscope is quite versatile. It can drive nails and examine small items. So, choose a microscope.
Great video, I'm so glad that TH-cam recommended your channel, I found myself doing a lot of mistakes that you explain in your videos and they improved my skills. Thanks!
Interfaces aims to define contract and provide definitions to the classes. The interfaces and types may look same and let you exhcnage. However, both types and interfaces have different meanings and hence different use cases!
I must say I was skeptical, but that was quite convincing 🤔
Very Interesting !
I believe we can also use Pick keyword to assign part of a type
to me interface and class were designed for people from OOP language (Java, .Net., python, Ruby, C...) switch to JS.
So, I use type over all interface, because I don't want to see any classes in my Typescript project : Composition over Inheritance :).
Code should typically be open to extension and closed to modifications and I find interfaces enabling this behavior intrinsically. Interestingly since JavaScript is really loose in their definition Types tend to be a preferable construct as it mirrors this flexibility while offering observability. I tend to use Types to describe data and transient information while I lean on interfaces for classes and business logic
Found the C# dev
I mean I dabbled a little😛
Great videos!
Very helpful, thanks :)
To keep the comparisons fair, I think we should just limit it to the things that BOTH are designed to be able to do,. In this case, it’s defining the shape of objects. Then we compare how good each is at doing those things. Otherwise it’s gonna be apples and oranges.
Interface Problem 2 is the exact reason I DON'T use Types... saying this could be an array or a string means any consumer of that data has to account for both. A type should be a single, immutable thing.
I had this conversation with my colleague and I tried to convey the differences between Interfaces and types and it wasn’t easy 😅 thanks for this thorough explanation. I also agree that using type works cleaner than interfaces