Hey Kyle! Loving all the TS content coming out of your channel. Wanted to drop by with a clarification that probably ALSO needs to be on my types vs interfaces video. When we're talking about performance with types vs interfaces, the difference is negligible when just declaring basic object types. The real performance gap is between intersections (&) and 'extends'. There is a pretty big gulf in performance between them - intersections are bloody hard for TS to resolve and so take a lot longer. Using extends is much easier and also comes with some correctness guarantees. I've seen a lot of folks in the community moving towards interfaces for that reason - interface extends really can speed up your TS codebase by a large factor. I also neglected to mention this in my types vs interface video, it's a nasty little nuance that isn't clear on first look. Love your stuff as always!
But extends and intersections serve different purposes. I think extends and union are more similar. Interfaces have no ability that I'm aware of for intersections.
I think I understand what you mean now. I was thinking of intersections on unions, and they work completely differently on unions. Intersections on object types are indeed basically the same as extends on interfaces. It's a little surprising that it would be a lot slower for types, but I guess that makes sense when they're capable of so much more.
To be very honest, this debate is completely unnecessary for me, I have used both, but I never found i have a huge problem just because i use interface, not type and vice versa.
But you actually supported they advice, because they say you should use types if you need it’s features. And this is what you showed. Personally I dont see an issue with mixing them up, we do it all the time
agreed, problem with coding youtubers is that they've never worked in the last few years so they just keep spouting nonsense that no one cares about at work.
Imagine opening every file and it uses different things, when importing something you never know if it is an interface or type means you never know if you can use generic types or type utility functions is pretty annoying. I’d rate this higher than a lot of other things in terms of things to agree on in a codebase.
@@SpeakChinglishif you use VS Code or most any other IDE then there is no need. Further most the time I just don’t care. Type?? Interface?? Most the time it doesn’t matter. And it is easy to change one to the other when the need arises.
1. Types intersection is NOT equal to extending interfaces. Intersect two types like { name: string } & { name: number } an see what happens. And happens "{ name: never }" instead of an error. Good luck tracking that in a project with more or less big types structure. 2. Types for some reason have an implicit index signature, which will bite you when you less expect it. When you denied to pass "just an object" to your func, for example, because that object "does not have an index signature", suddenly. Overall, this whole video sounds like "oh, I cannot use same syntax for two totally different tools with different tasks, so I'll use just one of them". What kind of arguing is that? Please don't do this.
1. To play devil's advocate, that isn't difficult to track in a large project at all. It becomes obvious as soon as you start actually using the `never` type, because then you'll see a type error, and it's no harder to fix than for interfaces (e.g. by removing or `Omit`ting the conflicting key). 2. There's a trade-off here; interfaces' explicit index signatures can also lead to unsafety. I recently tried to make a `Serializable` utility type, but my serializable interfaces weren't assigable to it because TS knows they can be extended to become unserializable (even though I know mine won't be). So I had to make my interfaces extend `interface SerializableRecord { [key: string | number]: Serializable | undefined }`. In a way, this is safer now that nobody can extend my interfaces to be unserializable. But in another way, it's less safe now that I can set nonexistent fields on my interfaces (since they're `Serializable | undefined`) without seeing a TS error, and I may not find out until runtime in production. And not only that, but with the explicit index signature, my classes could no longer implement my interfaces, since classes can't let any string index them. So I was practically forced to use types instead of interfaces.
Still learning here, are you saying interfaces can solve that particular issue? Such as: interface one {name: string} interface two extends one {name: number} that throws an error right? So is the benefit here that with interfaces, this gives an error and we realize sooner so we don't get the issue of "{ name: never }"
@@Nelsonm97 That is what they were saying in their first point, yes. (And I don't think this is an important point in favor of interfaces, as I explained in my previous comment.)
Another benefit of interfaces over types is that errors are so much easier to read. With types, it just spits out every property name which can get crazy when there are a lot of props, wheras with interfaces it just shows the interface name. I tend to use types more than interfaces, but I am torn on the issue because of the error messaging.
@@dhedarkhcustard I don´t think he means it shows you the values of the object. Rather that instead of MyUser it would show { Username: string, Password: string } & { moreStuff: number } & .... Some typescript type declarations get crazy out of hand its not obvious what type you are using when looking at a wall of props like that you don´t even know you are using a type, maybe it´s just inline with the variable and there is no type declaration to be found in your project.
Interfaces are made to represent objects and DTOs. Types are made to make few types work as close as primative types, but it can go as complex as you need.
I'm not convinced. I generally use interfaces for objects, and types for single liners like primitives or utility types. I find they play well together and don't see the issue with mixing them any more than mixing variable types.
When you start to wan to make unions/intersections or Omit, pick and many operations you see yourself using types instead of interfaces. The fact is, if you want consistency then you’ll not use interfaces
@@ChibiBlasphem I don't know if I agree with the "consistency" argyment. There are times to use interfaces, and times to use types. I feel like that logic would be consistent with not using any classes becuase you prefer functions. They both have their time and need and though you can pretty much do anything in Javascript with a function, there are times that you should just use a class.
@@justinwallace2321 And the only times when you want to use interfaces is for extending it because it's the only thing type aliases doesn't supports it. In every other cases types alias do the job and you get 1. Consistency, 2. Seeing an interface means it's meant to be extended, so clarity.
For me interfaces should be used when you want to expose a consistent API and make something open to extension but closed to modification where as use types for stuff you return from methods or functions For example, a database call to fetch a user by ID should return a user *type* but a class responsible for calling the database should implement an *interface*
Simple question, what advantage does it give you other then doing this because it feels right? It doesn't have any advantage at all. Doesn't help you read code faster, doesn't do pretty much anything.
Why though? There's literally nothing in one or the other that offers better suitability for those use cases. Even worse, the caller won't even realize the difference.
@@xromasik Making semantic sense is an advantage in itself. Interfaces make sense when you're going for an object oriented approach since multiple classes can implement multiple interfaces and can be used interchangeably but you cannot make a class implement a type. However I don't see much use of an interface when you're working with a functional approach, so as I said it's better for functions or methods to use types
@@truevelvett Imagine you want to store some sort of data but you don't want to worry about how it's stored (it might be stored in a JSON file, in memory or in an SQL database) Well, simply create an interface that defines a bunch of methods like "addUser", "getUser", "deleteUser", etc and based on your use case implement that interface that stores the user object somewhere. *But now the cool thing is that if in the future you decide to move from let's say storing in a JSON file to storing user details in an SQL server, all you have to do is define a new class that implements the interface that you defined and replace "new UserFileService()" with "new UserSQLService()" without touching the rest of your code*
I got your point, but i prefer to use Type like a "primitive" and Interface to describe an object. and... To use OR with interface, you just need to declare 2 or more interfaces and call after, like: interface A { a: string } interface B { b: number } const obj: A | B .... 🙃
One thing you don't mention about the benefits of interfaces over types is that interfaces are more OOP while types are more useful to share data around. Interfaces can have functions that are defined to have patterns that are predictable in your code base where the responsibilities are split between your views and your business logic. But, of course, in the front-end, it has less importance as you're mainly just sharing data around your components.
"More OOP" isn't a selling point. For the typical 'business app' types are the way to go as you shouldn't be using interface merging when you control the source anyway.
"in frontend"? In frontend usually doesn't matter because React is Functional Programming orientated, not because is frontend. You can write backend code in Functional Programming too, in my opinion if you're writing a API you SHOULD write it in Functional Programming, using OOP for unidirectional events is mostly overhead, and in TS can lead to very bad code, for example Nestjs with decorators.
@@adambickford8720 This is the wrong way to frame the topic. It shouldn't be "just use types" or "just use interfaces". For beginners there's already a sufficiently simple heuristic that you shouldn't have to say something so blunt -- object types are restrictive whereas interface types are permissive.
I cannot agree with these reasons at all. Interfaces come from the world of polymorphism (and OO for that matter), while types come from the world of JavaScript being a free for all weak type system, where anything can be anything and thus types are a mandatory feature. Union types make absolutely no sense in case of polymorphism and therefore you don't need them at all in this case. If you decide to refrain from polymorphism that doesn't mean that Interfaces are useless, it's just means you are having completely different approach in modelling your data structures.
Simply advocating to use types everywhere because it's one unified thing across your codebase is not the best argument. That's like saying "we'll always use `let` because you can do more than with `const`, so if you only use `const` you'll have to switch some to `let` and then you'll have a mix of `let` and `const` in your code".
When i started to learn typescript i used interface wherever i could. Couple years ago i switched to use types everywhere and only use interfaces for OOP purposes and I don't even know the reason I switched. But from my experience, most of the times you will do fine using one or another. (for instance a simple component props definition).
I would generally use interfaces as long as they are faster, but aliases have one major feature, means mapping type MappedTypeWithNewProperties = { [Properties in keyof Type as NewKeyType]: Type[Properties] }
I'm kinda surprised, given Kyle's previous tutorial videos where he uses types, that he didn't mention that the biggest benefits of using types is they can be combined with utility types to create the desired type from different types/interfaces. Things like Awaited, Partial, Readonly, etc. Example, you can't define an async/await function type with interfaces or types alone but you can do it by combining a type with Promise and Awaited.
I think you misunderstand what an interface is. An interface is like a "descriptor" = it describes how you can use the object (what properties you can expect, as well as what functions it provides). Here is an example: interface cat { name: string; age: number; meow(): void; } class Cat implements cat { name: string; age: number; meow(): void { console.log('meow'); } // but your class can have other properties and methods too color: string; }
@@heiko3169 I know what is an interface in typescript. I'm saying that both types and interfaces can be used together with utility types to create very powerful types that otherwise cannot be created with types or interfaces alone.
it is also possible to "extract" a type definition out of an interface if you need to. interface User { name: string; age: number; } const name: User["name"] = "Byron";
@@offroaders123 not in my experience, but I'd love to see a playground that proves me wrong. I've only needed/wanted to do this a few times, so it isn't a compelling reason for me to personally use interfaces or types all the time.
Naaah. Interface is for object structure. Types, well, for types, primitive style. Why would you want to use interface for the role of a types? I don't get it.
I feel like commenting on this will be pointless... I use objects 90% of the time to pass data around. When you need a simple argument for a function you do NOT need a type defined for it because you can inline the type and inference does the rest. Same goes for creating variables, you just inline the type. If you need a union of 2 objects then you make a union type from the interfaces. Interfaces hold you accountable for thinking about what you make and use instead of lazily creating types for everything that doesn't need it. Most of the cases you don't even need to export your interfaces unless you plan to use them inside a callback or something similar. It's funny how much flack I get for using classes and enums when they come with many benefits if you use them correctly.
If you're using mostly Classes in TS, without a doubt your introducing unnecessary overhead to your code, and in my opinion that's very bad. You're like going against the language trying to recreate OOP only languages.
Why is creating types lazy while interfaces are not? You can create an object type and specify that a class implements that type, just like with an interface. I don't see any benefit from using an interface.
If you ignore OOP using only the type keyword may be fine. To clarify on the interface and type keywords: Implicitely when you define a data structure with no values, you are defining an interface, e.g. { val: string } To use it you give the interface a name, e.g. interface Foo { val: string } The type keyword is a bit misleading. It is essentially an alias for an interface or a combination of interfaces, e.g. type Bar = string | Foo; Writing type Foo = { val: string }; is essentially defining an interface with no name and assigning it to an alias. Why create an alias of an interface instead of using it directly? In programming it‘s always better to use the simplest/minimal approach: If you can use primitive types use them instead of complex interfaces/objects. If you need simple data structures use interfaces. If you need union/or types use the type keyword.
type cannot be overwritten but you can overwrite interface.. for example use type to model and validate data type in the props of a UI component, so imagine you are bulding e-commerce application you have a customer object from a data base this object has a lot of connections to order object and other objects, and you're in the front-bulding an `order-history` page for the customer, your component will need order history list of specific customer and maybe a links to products in this order list and date or maybe payment method or delviery type now you're infornt of a combination of data types from more than one object, then create a `type` to model and validate the data for your UI component, you can use interface ofcourse but interface meant for customer object itself while type it could be a data in UI props or state.
After reading the comments I'm convinced that the people hard disagreeing with this take come from the world of OOP and are just used to interfaces. It seems many people don't realise classes can implement types, just like interfaces. In pretty much any situation you would want an interface it can be substituted for a type. So, why is this such a hot debate?
This is not the first video I see about types and interfaces and every time it is about the declaration of some object or primitive. You can choose whatever you want to describe your data, it mostly depends on your context anyway. However, I haven't seen anybody talk about the usage scenario of each. For instance, if you have a function with a parameter, declaring that this parameter is an Interface will enforce the value passed to this function to at least matches the interface declaration! The value itself can be declared as a type, a class, an anonymous object. I feel this feature is underrated and never included in this kind of discussion. Cheers ;)
I dont see the first problem as a problem. Seems same like saying "you can use either let, or const". It is not complicated or harder to read, both have its use cases, so use it. If you use interfaces, but types for single types/unions, why not?
Im pretty sure both exist for a reason and in every case it makes sense to decide to use one over the other. There is recommendations that you should use the smallest type possible of things. If types are a superset and you dont neet the additional features of types, it doesnt make Sense to use them.
I feel like intention matters too, especially for maintenance. Interface has a very clear definition across languages. And, that context should be preserved in typescript too. With that being said, I do end up using type more than interface, but I consistently use interface when I’m creating an abstraction/contract and type when I’m creating a type of something. I appreciate when I am in a codebase that does this consistently.
That's a great one also! I can't remember if it's with the & or the | operator, but I think you can create overloads with the type keyword using those operators as well.
I use the "interface" when I need to describe a model or some shape with methods. A "type" is used when I need to make a union, intersection, or get some other types using the utility types. Type cannot be implemented by the class, interface can. Interface has its own purpose that you did not mention, it is an abstraction and used in Design Patterns (SOLID principles)
Coming from OOP into TS I perceive the type/interface distinction to be very poorly designed. There are no clear use cases, they both kinda do the same thing but they don't, the naming is unintuitive, it feels disconnected from JS, and I end up just using what works and fix it when it breaks, which is what TS was supposed to prevent me from doing, or change type/interface on the fly to fit my needs forcing me to be aware of all the other code that references the type, and for a big project - it's painful. It feels like I am fighting with TS all the time. Why isn't there smth like @extendable decorator that you put before a type that lets you extend a type? IDK, it makes no sense to me.
If the file is globally-scoped, yes. But if it's a module, it will not merge. Even when each is exported from those separate modules, they will not merge. So modules can really help prevent things like that.
You can just use the | operator at the variable definition level, or am I wrong? This actually feels like cleaner code to me, because you define your interfaces, and at the var level you define which types to adhere to. And if you use interfaces in that way, I don't see the purpose of renaming base types (losing both advantages you summed up). I'm still pretty new to typescript (though not to programming), so still figuring things out... like: interface i1 { name: string } interface i2 { age: number } const user : i1 | i2 = { name: "test" }
You actually CAN do with interfaces what | does for types: just create third interface and make both types extend from it. I know it's mouthful, but it is possible. I personally lean towards types - they remind me of haskell syntax which warms my heart. Oh, and I also dislike this "extending interface" thing - I'd rather see it explicit, like in C# with "partial" keyword.
in general Type aliases offer a more convenient way to use utility types and describe tuples, while interfaces can also achieve the same but with a less elegant syntax.
IMHO This kind of videos foment the use of bad practices with new developers, the whole reason TS exists is to avoid this kind of implementation from JS but i guess they couldnt completely avoid it, the whole point of TS is to have typed variables so you know what to expect with those types you basically return to the old JS way where you could find any type and you wouldn’t know if the type is correct or not, which leads to bugs like NAN, or 1+1 = 11
I don't really think the message to take away from this is avoiding interfaces and to use types for everything. If you want to define a minimum structure that all objects being passed into a function or to be assigned to a specific property/variable must fit, than using an interface is perfectly reasonable. If you're wanting define a thing that can only be a union of some literal values then use a type or to do something more complicated like a utility then use a type. Lets not forget, an interface can inherit from a type so there is absolutely no reason to not use both and just use what's appropriate for your uses it doesn't make a code base any more or less complicated by exclusively using one or another, and as others have pointed out there is specific quirks to each that are not immediately obvious or well documented that can bite you in the ass if you exclusive used types.
It's really simple. Type for data. They are equivalent to 'records' in Functional Programming. Types shouldn't have functionality. Interface is synonymous to API and contracts. Hence, use them when you are doing services aka functionality.
I feel like type more coincides with javascripts natural dynamic nature. So if JS is your first or preferred language you'll feel more at home with type for almost everything only complicate code as much as necessary lol . Where as interface is more rigid like a more strictly OOP language like c# or java for example so people whose go to langage are more along those lines, may see a different reason for using types and interfaces at certain points in their code.
People often mix up these two concepts due to a poor understanding of types and interfaces. The purpose of an interface is to provide type information on classes, and this is conceptually distinct from types like strings, integers, or object literals in JavaScript. Given that JavaScript is prototype-based and object-oriented, the notion of classes doesn't truly exist; it's essentially syntactic sugar to emulate classic object-oriented programming. As a result, the use of interfaces in JavaScript doesn't align entirely with their traditional role. However, even in this context, there is a correct and incorrect way to use interfaces. Essentially, if one is working with classes, they should use interfaces; otherwise, they should stick to types. This approach reduces confusion and facilitates a smoother transition to working with genuinely object-oriented languages, such as C#.
It's not true that you can't use conditions with interfaces in TypeScript. They're actually quite powerful. You don't always need to use extends with interfaces; there's more you can do with them, like combining them together or having conditional types based on their content. Interfaces are great for defining the shape of objects: they're a bit stricter, which is good for making sure your objects have the right structure. Types, on the other hand, are more flexible. They can describe a bunch of different things, not just objects. But because they're so flexible, they can sometimes be too loose for defining objects. That's why, when you want to be really clear about the structure of your objects, it's better to use interfaces instead of types. I don't think you really understood how to use interfaces properly, and this video is misleading on many points.
May I say that in a world of approximate developers, always in hurry, "restrictive" when features are not needed, or where you are not at all aware in what you doing, it is better(safer?) than "versatile"? That because when you reach a cul-de-sac using interfaces, you forced to ask yourself "am I proceeding in the right way?", then eventually go for types. It might impact with the developing speed, but for sure that improves your software design quality.
But why not just use a string instead of SType? Also by defining a type as both string and number, you break with the type strong language, so you might as well just use “var” and have it as a variant type.
i'm usually use interface if i want to pass a type on an object. Type i usually use when i want to combine a type or create union type Interface1 & Interface2 "one" | "two" | number my question is should i use I before the name of the interface? eg, IUser, ITemplate, IBook
Just want to take this chance to thank you Kyle for your tutorials. Your videos were one of the main reasons I landed a ReactJS job. Truly appreciate you! Greetings from Philippines. :)
I believe that borrowing interface and type definitions from other languages can enhance your understanding and application of each concept. For instance, I prefer working with definitions from Golang because it benefits from the fact that both JS and Golang are functional languages. So, I agree that this recommendation sounds a bit off. Thank you for the video and for the subject!
The difference between a good coder and a good engineer is knowing when to use your tools properly and not just relying on a single paradigm. Interfaces for object types and types for typed instances. Inheritance can only be done with interfaces and helps with conceptually linking your objects. Wouldn't you rather have an interface that extends your shape rather than define a type that has a union of all shapes? This concept is like always resorting to const objects for your functions to avoid changing "this"
interface and type are differents. Type are use to create object, interface to sign a contract that a Type have to follow, then you can script based on this contract and not a strict type and this contract can be shared by many types. This is a basic in many language.
Truly disappointed with this video. Typescript literally tells you "Use interfaces until you need the features of types", but then Kyle makes a video listing all the features of types and saying that's why you should always use types, whether you need those features or not (and a lot of the time, you really don't). Types serve a purpose, interfaces serve a purpose, you should've rather made a video explaining how to know when to use types or interfaces. And the whole mixing types and interfaces in the codebase comment is bogus, that's like saying "Always use 'const' instead of 'let' because const has all these features and let only does this"... Seriously Kyle 🤦♂💔
Worst thing about interfaces imo is the bad intellisense in VS Code. It only shows the interface name but not the definition of what is inside. That was my deal breaker with interfaces.
To me it doesn't really matter that much. I use both, and I don't see how you could ever have it come up as an issue. If something can't be done with a type, use an interface, and same in the other case. They're used the same so it doesn't really matter.
Always use interfaces unless you need the functionality of a type. Interfaces are much faster and saves lots of compile time on large projects.. Its still true nowadays
that's largely a myth. matt pocock even clarified in one his videos that the speed difference on a large project was too small to even matter. they probably are faster, but not by much, the difference is miniscule.
I understand your point, but I'm not entirely convinced. Instead of using 'SType', you could simply use 'string | number' wherever necessary. Why bother defining it as a separate type? In case of the two objects, you can go for an Inteface1 | Interface2 approach. Its completely possible, or am I missing something? interface Broccoli { name: string; } interface Banana { age: number; } const user: Broccoli | Banana = { name: "Doemser" }; same works for the "&" and how often do we have to deal with simple objects like the ones you showed? Additionally, while it's true that code needs to be simple, simplicity doesn't necessarily equate to writing one-liners. For me simplicity means making the code more comprehensible to other developers.. It seems that this boils down to personal or team preference rather than a definitive advantage.
Only thing I find problematic with interfaces is the merging. Many times I like to have a type "Props" for example, that is isolated per file, and if I use an interface, they all merge in the end, and that makes it a little complicated when working on large projects. Suddenly for a component, you have 20 props, when in the definition file you specifiy like 3.
I think the best way to accommodate for this is to use modules to break up your components, they will be scoped to each file, allowing you to use multiple of the same-named interface if you'd like to. Personally I like to name them uniquely to align with the name of the component so I can export it from the module as well, but if it's local to only the module, then I think it's ok if you all name them the same 🙂
Don't really have an opinon on this yet but I started doing this in my code: `React.ComponentProps`. I don't find that I'm often using props outside of the component instance, but when I do I reach for this. Especially when a 3rd party doesn't export them.
Why define a type or interface outside of your component declaration when you could inline it. Which has the benefit of intellisense showing the exact prop types instead of "MyComponentProps": export const MyComponent: React.FC = ({ isDisabled = false, color = "red", name }) => { ... };
@@dhedarkhcustard Defining it separately allows you to use the props as a specific type elsewhere in your codebase, simply by importing it. I guess you could also do that by extracting the parameter types of the component elsewhere yourself, but importing the interface itself seems a little more simple I feel like. Maybe it depends though. And if the props get too big over time, then having the destructuring and the type annotations in the same place can get larger over time, making things a little more cluttered. I want to try inlining it now though, like you said it does seem more simple to have them all in one place!
While I see the merit in using types, I personally prefer to use interfaces for my React components. I believe interfaces offer a clearer contract for components, enhancing code readability and maintainability. However, I do agree that types have their own advantages in specific scenarios. It seems like a balanced approach, utilizing both interfaces and types where appropriate, could be the most effective strategy
Interfaces do not provide a real contract like types do. Interfaces are designed to be augmented, so if I redefine any of your interfaces I can easily break this "contract" by adding any other definitions, and your components will have no idea of those changes.
Idk i always use types for you know types and interfaces when i want to enforce behaviour on a certain class, as a mostly Java/Kotlin coder I feel like these concepts are not well suited for JS.
I prefer types, but interfaces are significantly more performant (pretty important in huge codebases). Unless I'm misremembering this or they fixed it?
This works the same way with types or interfaces. When you use a TS type/interface it doesn't matter if it is a type or interface. They both work exactly the same when used. It is just in how they are defined that they differ.
Hey Kyle! Loving all the TS content coming out of your channel.
Wanted to drop by with a clarification that probably ALSO needs to be on my types vs interfaces video.
When we're talking about performance with types vs interfaces, the difference is negligible when just declaring basic object types. The real performance gap is between intersections (&) and 'extends'. There is a pretty big gulf in performance between them - intersections are bloody hard for TS to resolve and so take a lot longer. Using extends is much easier and also comes with some correctness guarantees. I've seen a lot of folks in the community moving towards interfaces for that reason - interface extends really can speed up your TS codebase by a large factor.
I also neglected to mention this in my types vs interface video, it's a nasty little nuance that isn't clear on first look.
Love your stuff as always!
I wanna kiss your forehead every waking hour 💋
But extends and intersections serve different purposes. I think extends and union are more similar. Interfaces have no ability that I'm aware of for intersections.
I think I understand what you mean now. I was thinking of intersections on unions, and they work completely differently on unions. Intersections on object types are indeed basically the same as extends on interfaces. It's a little surprising that it would be a lot slower for types, but I guess that makes sense when they're capable of so much more.
Speed up transpiling or runtime?
@@kevinclark1783 Transpiling
To be very honest, this debate is completely unnecessary for me, I have used both, but I never found i have a huge problem just because i use interface, not type and vice versa.
Kyle is great. But most TH-camrs need new content so yeah many times it’s not a big deal.
It's not a big deal but Consistency is good. Makes the code more readable
I find for exemple that the first reason is not really a problem
But you actually supported they advice, because they say you should use types if you need it’s features. And this is what you showed.
Personally I dont see an issue with mixing them up, we do it all the time
agreed, problem with coding youtubers is that they've never worked in the last few years so they just keep spouting nonsense that no one cares about at work.
If having to use types and interfaces together in the same codebase is your biggest problem then you are really having a sweet life
I was feeling the same thing 😅
Imagine opening every file and it uses different things, when importing something you never know if it is an interface or type means you never know if you can use generic types or type utility functions is pretty annoying. I’d rate this higher than a lot of other things in terms of things to agree on in a codebase.
@@SpeakChinglish There is a convention devs use:
Add 'I' to the name of an interface and 'T' to the name of a type.
IUser, TUser.
@@imdanteasynot all developers do that. Seeing such makes me want to puke.
@@SpeakChinglishif you use VS Code or most any other IDE then there is no need. Further most the time I just don’t care. Type?? Interface?? Most the time it doesn’t matter. And it is easy to change one to the other when the need arises.
1. Types intersection is NOT equal to extending interfaces.
Intersect two types like { name: string } & { name: number } an see what happens.
And happens "{ name: never }" instead of an error. Good luck tracking that in a project with more or less big types structure.
2. Types for some reason have an implicit index signature, which will bite you when you less expect it. When you denied to pass "just an object" to your func, for example, because that object "does not have an index signature", suddenly.
Overall, this whole video sounds like "oh, I cannot use same syntax for two totally different tools with different tasks, so I'll use just one of them". What kind of arguing is that? Please don't do this.
Fax
When this guy uploads a video, I always go to the comments to see the real LPT. I should thank him for that at least.
1. To play devil's advocate, that isn't difficult to track in a large project at all. It becomes obvious as soon as you start actually using the `never` type, because then you'll see a type error, and it's no harder to fix than for interfaces (e.g. by removing or `Omit`ting the conflicting key).
2. There's a trade-off here; interfaces' explicit index signatures can also lead to unsafety. I recently tried to make a `Serializable` utility type, but my serializable interfaces weren't assigable to it because TS knows they can be extended to become unserializable (even though I know mine won't be). So I had to make my interfaces extend `interface SerializableRecord { [key: string | number]: Serializable | undefined }`. In a way, this is safer now that nobody can extend my interfaces to be unserializable. But in another way, it's less safe now that I can set nonexistent fields on my interfaces (since they're `Serializable | undefined`) without seeing a TS error, and I may not find out until runtime in production. And not only that, but with the explicit index signature, my classes could no longer implement my interfaces, since classes can't let any string index them. So I was practically forced to use types instead of interfaces.
Still learning here, are you saying interfaces can solve that particular issue? Such as:
interface one {name: string}
interface two extends one {name: number}
that throws an error right? So is the benefit here that with interfaces, this gives an error and we realize sooner so we don't get the issue of "{ name: never }"
@@Nelsonm97 That is what they were saying in their first point, yes. (And I don't think this is an important point in favor of interfaces, as I explained in my previous comment.)
Another benefit of interfaces over types is that errors are so much easier to read. With types, it just spits out every property name which can get crazy when there are a lot of props, wheras with interfaces it just shows the interface name. I tend to use types more than interfaces, but I am torn on the issue because of the error messaging.
How is showing just the interface name better than showing the exact parts of the type that break better?
@@dhedarkhcustard I don´t think he means it shows you the values of the object. Rather that instead of MyUser it would show { Username: string, Password: string } & { moreStuff: number } & .... Some typescript type declarations get crazy out of hand its not obvious what type you are using when looking at a wall of props like that you don´t even know you are using a type, maybe it´s just inline with the variable and there is no type declaration to be found in your project.
You should definitely read about what interfaces are used for
Interfaces are made to represent objects and DTOs.
Types are made to make few types work as close as primative types, but it can go as complex as you need.
I'm not convinced. I generally use interfaces for objects, and types for single liners like primitives or utility types. I find they play well together and don't see the issue with mixing them any more than mixing variable types.
When you start to wan to make unions/intersections or Omit, pick and many operations you see yourself using types instead of interfaces. The fact is, if you want consistency then you’ll not use interfaces
@@ChibiBlasphem that's what i mean by utility types. Types work well for single liners.
js, primitives (¬ ¬)
@@ChibiBlasphem I don't know if I agree with the "consistency" argyment. There are times to use interfaces, and times to use types. I feel like that logic would be consistent with not using any classes becuase you prefer functions. They both have their time and need and though you can pretty much do anything in Javascript with a function, there are times that you should just use a class.
@@justinwallace2321 And the only times when you want to use interfaces is for extending it because it's the only thing type aliases doesn't supports it. In every other cases types alias do the job and you get 1. Consistency, 2. Seeing an interface means it's meant to be extended, so clarity.
For me interfaces should be used when you want to expose a consistent API and make something open to extension but closed to modification where as use types for stuff you return from methods or functions
For example, a database call to fetch a user by ID should return a user *type* but a class responsible for calling the database should implement an *interface*
Yeah that sounds pretty solid.
Simple question, what advantage does it give you other then doing this because it feels right? It doesn't have any advantage at all. Doesn't help you read code faster, doesn't do pretty much anything.
Why though? There's literally nothing in one or the other that offers better suitability for those use cases. Even worse, the caller won't even realize the difference.
@@xromasik Making semantic sense is an advantage in itself. Interfaces make sense when you're going for an object oriented approach since multiple classes can implement multiple interfaces and can be used interchangeably but you cannot make a class implement a type.
However I don't see much use of an interface when you're working with a functional approach, so as I said it's better for functions or methods to use types
@@truevelvett Imagine you want to store some sort of data but you don't want to worry about how it's stored (it might be stored in a JSON file, in memory or in an SQL database)
Well, simply create an interface that defines a bunch of methods like "addUser", "getUser", "deleteUser", etc and based on your use case implement that interface that stores the user object somewhere.
*But now the cool thing is that if in the future you decide to move from let's say storing in a JSON file to storing user details in an SQL server, all you have to do is define a new class that implements the interface that you defined and replace "new UserFileService()" with "new UserSQLService()" without touching the rest of your code*
I got your point, but i prefer to use Type like a "primitive" and Interface to describe an object.
and... To use OR with interface, you just need to declare 2 or more interfaces and call after, like:
interface A {
a: string
}
interface B {
b: number
}
const obj: A | B ....
🙃
Thank you! I really like this pattern too.
One thing you don't mention about the benefits of interfaces over types is that interfaces are more OOP while types are more useful to share data around. Interfaces can have functions that are defined to have patterns that are predictable in your code base where the responsibilities are split between your views and your business logic. But, of course, in the front-end, it has less importance as you're mainly just sharing data around your components.
Yep. looks like Kyle doesn't do much OOP at all to understand the difference.
@@harag9 You can make class implement a type if that type is nonunion object-like type. No any difference for OOP.
"More OOP" isn't a selling point. For the typical 'business app' types are the way to go as you shouldn't be using interface merging when you control the source anyway.
"in frontend"? In frontend usually doesn't matter because React is Functional Programming orientated, not because is frontend. You can write backend code in Functional Programming too, in my opinion if you're writing a API you SHOULD write it in Functional Programming, using OOP for unidirectional events is mostly overhead, and in TS can lead to very bad code, for example Nestjs with decorators.
@@adambickford8720 This is the wrong way to frame the topic. It shouldn't be "just use types" or "just use interfaces". For beginners there's already a sufficiently simple heuristic that you shouldn't have to say something so blunt -- object types are restrictive whereas interface types are permissive.
I use interfaces to enforce the shape of classes.
I cannot agree with these reasons at all. Interfaces come from the world of polymorphism (and OO for that matter), while types come from the world of JavaScript being a free for all weak type system, where anything can be anything and thus types are a mandatory feature. Union types make absolutely no sense in case of polymorphism and therefore you don't need them at all in this case. If you decide to refrain from polymorphism that doesn't mean that Interfaces are useless, it's just means you are having completely different approach in modelling your data structures.
Simply advocating to use types everywhere because it's one unified thing across your codebase is not the best argument. That's like saying "we'll always use `let` because you can do more than with `const`, so if you only use `const` you'll have to switch some to `let` and then you'll have a mix of `let` and `const` in your code".
I'm originally an OOP programmer and so I like to use inheritance. I like to define interfaces that can extend each other.
When i started to learn typescript i used interface wherever i could. Couple years ago i switched to use types everywhere and only use interfaces for OOP purposes and I don't even know the reason I switched. But from my experience, most of the times you will do fine using one or another. (for instance a simple component props definition).
I would generally use interfaces as long as they are faster, but aliases have one major feature, means mapping
type MappedTypeWithNewProperties = {
[Properties in keyof Type as NewKeyType]: Type[Properties]
}
I'm kinda surprised, given Kyle's previous tutorial videos where he uses types, that he didn't mention that the biggest benefits of using types is they can be combined with utility types to create the desired type from different types/interfaces. Things like Awaited, Partial, Readonly, etc. Example, you can't define an async/await function type with interfaces or types alone but you can do it by combining a type with Promise and Awaited.
I think you misunderstand what an interface is. An interface is like a "descriptor" = it describes how you can use the object (what properties you can expect, as well as what functions it provides).
Here is an example:
interface cat {
name: string;
age: number;
meow(): void;
}
class Cat implements cat {
name: string;
age: number;
meow(): void {
console.log('meow');
}
// but your class can have other properties and methods too
color: string;
}
@@heiko3169 I know what is an interface in typescript. I'm saying that both types and interfaces can be used together with utility types to create very powerful types that otherwise cannot be created with types or interfaces alone.
it is also possible to "extract" a type definition out of an interface if you need to.
interface User {
name: string;
age: number;
}
const name: User["name"] = "Byron";
I feel like this is possible with a type definition also?
@@offroaders123 not in my experience, but I'd love to see a playground that proves me wrong. I've only needed/wanted to do this a few times, so it isn't a compelling reason for me to personally use interfaces or types all the time.
It is possible to "extract".
interface UserI {
name: string;
age: number;
}
const usernameI: UserI["name"] = "Byron";
type UserT = {
name: string;
age: number;
}
const usernameT: UserT["name"] = "Byron";
Naaah. Interface is for object structure. Types, well, for types, primitive style. Why would you want to use interface for the role of a types? I don't get it.
It's quite the opposite. He wants to use types for the role of interfaces
I feel like commenting on this will be pointless...
I use objects 90% of the time to pass data around.
When you need a simple argument for a function you do NOT need a type defined for it because you can inline the type and inference does the rest.
Same goes for creating variables, you just inline the type.
If you need a union of 2 objects then you make a union type from the interfaces.
Interfaces hold you accountable for thinking about what you make and use instead of lazily creating types for everything that doesn't need it.
Most of the cases you don't even need to export your interfaces unless you plan to use them inside a callback or something similar.
It's funny how much flack I get for using classes and enums when they come with many benefits if you use them correctly.
If you're using mostly Classes in TS, without a doubt your introducing unnecessary overhead to your code, and in my opinion that's very bad. You're like going against the language trying to recreate OOP only languages.
Why is creating types lazy while interfaces are not? You can create an object type and specify that a class implements that type, just like with an interface. I don't see any benefit from using an interface.
I don't see why you would oppose using both, doesn't complicate the code at all.
If you ignore OOP using only the type keyword may be fine.
To clarify on the interface and type keywords:
Implicitely when you define a data structure with no values, you are defining an interface, e.g. { val: string }
To use it you give the interface a name, e.g. interface Foo { val: string }
The type keyword is a bit misleading. It is essentially an alias for an interface or a combination of interfaces, e.g. type Bar = string | Foo;
Writing type Foo = { val: string }; is essentially defining an interface with no name and assigning it to an alias. Why create an alias of an interface instead of using it directly?
In programming it‘s always better to use the simplest/minimal approach:
If you can use primitive types use them instead of complex interfaces/objects.
If you need simple data structures use interfaces.
If you need union/or types use the type keyword.
Interface is for declaring class in OOP and type is for declaring Datatypes.
type cannot be overwritten but you can overwrite interface.. for example use type to model and validate data type in the props of a UI component, so imagine you are bulding e-commerce application you have a customer object from a data base this object has a lot of connections to order object and other objects, and you're in the front-bulding an `order-history` page for the customer, your component will need order history list of specific customer and maybe a links to products in this order list and date or maybe payment method or delviery type now you're infornt of a combination of data types from more than one object, then create a `type` to model and validate the data for your UI component, you can use interface ofcourse but interface meant for customer object itself while type it could be a data in UI props or state.
I use interfaces for function props and class definitions and types for everything else.
I guess one useful feature of interfaces is also that they can be implemented by classes, right? Or can that be covered with types as well?
sure you can do that with types no problem
@@dasten123 Awesome, I wasn't aware of that - thanks :)
After reading the comments I'm convinced that the people hard disagreeing with this take come from the world of OOP and are just used to interfaces. It seems many people don't realise classes can implement types, just like interfaces. In pretty much any situation you would want an interface it can be substituted for a type. So, why is this such a hot debate?
Clarity: they do different things 🙂
This is not the first video I see about types and interfaces and every time it is about the declaration of some object or primitive. You can choose whatever you want to describe your data, it mostly depends on your context anyway. However, I haven't seen anybody talk about the usage scenario of each. For instance, if you have a function with a parameter, declaring that this parameter is an Interface will enforce the value passed to this function to at least matches the interface declaration! The value itself can be declared as a type, a class, an anonymous object. I feel this feature is underrated and never included in this kind of discussion. Cheers ;)
Doesn't that work exactly the same if you use a type instead?
@@ollierkul ye it does. typescript is a structural language so the usecase hes describing is completely the same for types
I dont see the first problem as a problem. Seems same like saying "you can use either let, or const". It is not complicated or harder to read, both have its use cases, so use it. If you use interfaces, but types for single types/unions, why not?
Im pretty sure both exist for a reason and in every case it makes sense to decide to use one over the other. There is recommendations that you should use the smallest type possible of things. If types are a superset and you dont neet the additional features of types, it doesnt make Sense to use them.
I feel like intention matters too, especially for maintenance. Interface has a very clear definition across languages. And, that context should be preserved in typescript too. With that being said, I do end up using type more than interface, but I consistently use interface when I’m creating an abstraction/contract and type when I’m creating a type of something. I appreciate when I am in a codebase that does this consistently.
If I recall correctly, another feature exclusive of interfaces is the ability to define overloaded methods.
I do prefer types in most cases though!
That's a great one also! I can't remember if it's with the & or the | operator, but I think you can create overloads with the type keyword using those operators as well.
I use the "interface" when I need to describe a model or some shape with methods. A "type" is used when I need to make a union, intersection, or get some other types using the utility types. Type cannot be implemented by the class, interface can. Interface has its own purpose that you did not mention, it is an abstraction and used in Design Patterns (SOLID principles)
That's wrong though. Classes can implement types, just like interfaces.
Coming from OOP into TS I perceive the type/interface distinction to be very poorly designed. There are no clear use cases, they both kinda do the same thing but they don't, the naming is unintuitive, it feels disconnected from JS, and I end up just using what works and fix it when it breaks, which is what TS was supposed to prevent me from doing, or change type/interface on the fly to fit my needs forcing me to be aware of all the other code that references the type, and for a big project - it's painful. It feels like I am fighting with TS all the time. Why isn't there smth like @extendable decorator that you put before a type that lets you extend a type? IDK, it makes no sense to me.
Exactly my point. TS creates its own incomplete paradigm and did not borrow from accepted better ones
Pretty sure you can do interface SInter { name: string | number } with no problem. I use Angular & never create my own types.
Well, I use interface, generics and types as well.
Does this overriding of interfaces with the same name happen as well if they're in different files? because that could be a problem
If the file is globally-scoped, yes. But if it's a module, it will not merge. Even when each is exported from those separate modules, they will not merge. So modules can really help prevent things like that.
@@offroaders123 nice, thanks for clarifying.
Dude, how are you so spot on all the time??
You can just use the | operator at the variable definition level, or am I wrong? This actually feels like cleaner code to me, because you define your interfaces, and at the var level you define which types to adhere to. And if you use interfaces in that way, I don't see the purpose of renaming base types (losing both advantages you summed up).
I'm still pretty new to typescript (though not to programming), so still figuring things out...
like:
interface i1 {
name: string
}
interface i2 {
age: number
}
const user : i1 | i2 = { name: "test" }
You actually CAN do with interfaces what | does for types: just create third interface and make both types extend from it. I know it's mouthful, but it is possible. I personally lean towards types - they remind me of haskell syntax which warms my heart. Oh, and I also dislike this "extending interface" thing - I'd rather see it explicit, like in C# with "partial" keyword.
in general Type aliases offer a more convenient way to use utility types and describe tuples, while interfaces can also achieve the same but with a less elegant syntax.
Type status = "complete" | "incomplete"; is one I love very much
IMHO This kind of videos foment the use of bad practices with new developers, the whole reason TS exists is to avoid this kind of implementation from JS but i guess they couldnt completely avoid it, the whole point of TS is to have typed variables so you know what to expect with those types you basically return to the old JS way where you could find any type and you wouldn’t know if the type is correct or not, which leads to bugs like NAN, or 1+1 = 11
I don't really think the message to take away from this is avoiding interfaces and to use types for everything. If you want to define a minimum structure that all objects being passed into a function or to be assigned to a specific property/variable must fit, than using an interface is perfectly reasonable. If you're wanting define a thing that can only be a union of some literal values then use a type or to do something more complicated like a utility then use a type.
Lets not forget, an interface can inherit from a type so there is absolutely no reason to not use both and just use what's appropriate for your uses it doesn't make a code base any more or less complicated by exclusively using one or another, and as others have pointed out there is specific quirks to each that are not immediately obvious or well documented that can bite you in the ass if you exclusive used types.
Excellent video. I like how fast you speak because you get across what you want to say really quickly.
I totally agree about this, use type by default
There is a second benefit, errors will not include type names, interfaces most of the time do. Unless things changed since last time I worked with TS
It's really simple. Type for data. They are equivalent to 'records' in Functional Programming.
Types shouldn't have functionality.
Interface is synonymous to API and contracts. Hence, use them when you are doing services aka functionality.
What is the usecase for the first reason? I simply can write const user:string ='bla'
why should i make an "alias" for a simple string?
I feel like type more coincides with javascripts natural dynamic nature. So if JS is your first or preferred language you'll feel more at home with type for almost everything only complicate code as much as necessary lol . Where as interface is more rigid like a more strictly OOP language like c# or java for example so people whose go to langage are more along those lines, may see a different reason for using types and interfaces at certain points in their code.
Kyle, why would you make a type equal to string ? Just use string ? Am i missing something ?
Just to show you that you can't use interfaces outside objects
People often mix up these two concepts due to a poor understanding of types and interfaces. The purpose of an interface is to provide type information on classes, and this is conceptually distinct from types like strings, integers, or object literals in JavaScript. Given that JavaScript is prototype-based and object-oriented, the notion of classes doesn't truly exist; it's essentially syntactic sugar to emulate classic object-oriented programming. As a result, the use of interfaces in JavaScript doesn't align entirely with their traditional role.
However, even in this context, there is a correct and incorrect way to use interfaces. Essentially, if one is working with classes, they should use interfaces; otherwise, they should stick to types. This approach reduces confusion and facilitates a smoother transition to working with genuinely object-oriented languages, such as C#.
I too use type unless I need interfaces (I recall needing some advanced generic types in reducers that could only be done with interfaces)
It's not true that you can't use conditions with interfaces in TypeScript. They're actually quite powerful.
You don't always need to use extends with interfaces; there's more you can do with them, like combining them together or having conditional types based on their content. Interfaces are great for defining the shape of objects: they're a bit stricter, which is good for making sure your objects have the right structure.
Types, on the other hand, are more flexible. They can describe a bunch of different things, not just objects. But because they're so flexible, they can sometimes be too loose for defining objects. That's why, when you want to be really clear about the structure of your objects, it's better to use interfaces instead of types.
I don't think you really understood how to use interfaces properly, and this video is misleading on many points.
May I say that in a world of approximate developers, always in hurry, "restrictive" when features are not needed, or where you are not at all aware in what you doing, it is better(safer?) than "versatile"?
That because when you reach a cul-de-sac using interfaces, you forced to ask yourself "am I proceeding in the right way?", then eventually go for types.
It might impact with the developing speed, but for sure that improves your software design quality.
Please make a tutorial: NodeJS (web api) + htmx (frontend), simple CRUD operations
I use interface for classes and types for objects
I like this a lot, interfaces looks kinda unnecessary I don’t see why not use Type everywhere for consistency
This answers a question to another video of yours! Thank you thank you thank you!!!!
Yeah, you got me on to the type train a while ago, and now nobody is telling me otherwise. I like interfaces for the naming convention only.
But why not just use a string instead of SType? Also by defining a type as both string and number, you break with the type strong language, so you might as well just use “var” and have it as a variant type.
I’d be surprised if anyone took anything away from this video. Pure waffle.
Pro tip :
If you’re defining an interface, use interface
If you’re defining a type, use type
You’re welcome
🙂
Can class implement type?
i'm usually use interface if i want to pass a type on an object.
Type i usually use when i want to combine a type or create union type
Interface1 & Interface2
"one" | "two" | number
my question is should i use I before the name of the interface? eg, IUser, ITemplate, IBook
Interfaces is nice for inheritance
*type - defines what something is.
*interface - defines what is the origin of something.
Excellent explanation! 👏🏻
Wow, great explanation, thanks a lot! 👍
Just want to take this chance to thank you Kyle for your tutorials. Your videos were one of the main reasons I landed a ReactJS job. Truly appreciate you! Greetings from Philippines. :)
I believe that borrowing interface and type definitions from other languages can enhance your understanding and application of each concept.
For instance, I prefer working with definitions from Golang because it benefits from the fact that both JS and Golang are functional languages.
So, I agree that this recommendation sounds a bit off.
Thank you for the video and for the subject!
The difference between a good coder and a good engineer is knowing when to use your tools properly and not just relying on a single paradigm.
Interfaces for object types and types for typed instances.
Inheritance can only be done with interfaces and helps with conceptually linking your objects. Wouldn't you rather have an interface that extends your shape rather than define a type that has a union of all shapes?
This concept is like always resorting to const objects for your functions to avoid changing "this"
interface and type are differents. Type are use to create object, interface to sign a contract that a Type have to follow, then you can script based on this contract and not a strict type and this contract can be shared by many types. This is a basic in many language.
We could also use Type as a sign contract though right?
Truly disappointed with this video. Typescript literally tells you "Use interfaces until you need the features of types", but then Kyle makes a video listing all the features of types and saying that's why you should always use types, whether you need those features or not (and a lot of the time, you really don't). Types serve a purpose, interfaces serve a purpose, you should've rather made a video explaining how to know when to use types or interfaces.
And the whole mixing types and interfaces in the codebase comment is bogus, that's like saying "Always use 'const' instead of 'let' because const has all these features and let only does this"...
Seriously Kyle 🤦♂💔
This is the type of video that confuses people that are starting and discourage the devs.
For me interface is for implementing classes oop style. I use types until i need oop style interfaces
Worst thing about interfaces imo is the bad intellisense in VS Code. It only shows the interface name but not the definition of what is inside. That was my deal breaker with interfaces.
To me it doesn't really matter that much. I use both, and I don't see how you could ever have it come up as an issue. If something can't be done with a type, use an interface, and same in the other case. They're used the same so it doesn't really matter.
Always use interfaces unless you need the functionality of a type. Interfaces are much faster and saves lots of compile time on large projects.. Its still true nowadays
that's largely a myth.
matt pocock even clarified in one his videos that the speed difference on a large project was too small to even matter. they probably are faster, but not by much, the difference is miniscule.
I understand your point, but I'm not entirely convinced. Instead of using 'SType', you could simply use 'string | number' wherever necessary. Why bother defining it as a separate type?
In case of the two objects, you can go for an Inteface1 | Interface2 approach. Its completely possible, or am I missing something?
interface Broccoli {
name: string;
}
interface Banana {
age: number;
}
const user: Broccoli | Banana = { name: "Doemser" };
same works for the "&" and how often do we have to deal with simple objects like the ones you showed?
Additionally, while it's true that code needs to be simple, simplicity doesn't necessarily equate to writing one-liners. For me simplicity means making the code more comprehensible to other developers..
It seems that this boils down to personal or team preference rather than a definitive advantage.
이거 궁금했는데, 감사합니다. 잘 보았습니다.
For me to have variable which can be string or number is not advantage at all. As well you can just don’t use TS.
Only thing I find problematic with interfaces is the merging. Many times I like to have a type "Props" for example, that is isolated per file, and if I use an interface, they all merge in the end, and that makes it a little complicated when working on large projects. Suddenly for a component, you have 20 props, when in the definition file you specifiy like 3.
I think the best way to accommodate for this is to use modules to break up your components, they will be scoped to each file, allowing you to use multiple of the same-named interface if you'd like to. Personally I like to name them uniquely to align with the name of the component so I can export it from the module as well, but if it's local to only the module, then I think it's ok if you all name them the same 🙂
You can use it like this:
interface YourComponentNameProps {}
export function YourComponentName(props: YourComponentNameProps) {}
Don't really have an opinon on this yet but I started doing this in my code: `React.ComponentProps`. I don't find that I'm often using props outside of the component instance, but when I do I reach for this. Especially when a 3rd party doesn't export them.
Why define a type or interface outside of your component declaration when you could inline it. Which has the benefit of intellisense showing the exact prop types instead of "MyComponentProps":
export const MyComponent: React.FC = ({ isDisabled = false, color = "red", name }) => { ... };
@@dhedarkhcustard Defining it separately allows you to use the props as a specific type elsewhere in your codebase, simply by importing it. I guess you could also do that by extracting the parameter types of the component elsewhere yourself, but importing the interface itself seems a little more simple I feel like. Maybe it depends though. And if the props get too big over time, then having the destructuring and the type annotations in the same place can get larger over time, making things a little more cluttered. I want to try inlining it now though, like you said it does seem more simple to have them all in one place!
actually type concept is a bit weird (too dynamic, not oop). but as it supports with vs code, therefore it's fine
Do you have another channel where you play guitar?
While I see the merit in using types, I personally prefer to use interfaces for my React components. I believe interfaces offer a clearer contract for components, enhancing code readability and maintainability. However, I do agree that types have their own advantages in specific scenarios. It seems like a balanced approach, utilizing both interfaces and types where appropriate, could be the most effective strategy
Interfaces do not provide a real contract like types do. Interfaces are designed to be augmented, so if I redefine any of your interfaces I can easily break this "contract" by adding any other definitions, and your components will have no idea of those changes.
Idk i always use types for you know types and interfaces when i want to enforce behaviour on a certain class, as a mostly Java/Kotlin coder I feel like these concepts are not well suited for JS.
For no reason what-so-ever, I use type for objects and stuff, and only use interface when defining the parameters of a function / component.
Object oriented, mutable code benefits greatly from interfaces
amazing, thank you dude
the only thing i see is that he ain't using copilot 😂 he's the resistance XD, but also no line numbers??? gg good point bro!
As long as applications works flawlessly , use whatever suits. There is no right and wrong. Once your code base becomes huge, it does not matter .
What about Flow?
Is this guy running out of contents to output? Because this video was super unnecessary.
what about enums?
I prefer types, but interfaces are significantly more performant (pretty important in huge codebases). Unless I'm misremembering this or they fixed it?
TS team fix this years ago, but they forgot to update the docs like always.
very useful! thank u
What about class MyClass implements MyInterface{} ?
This works the same way with types or interfaces. When you use a TS type/interface it doesn't matter if it is a type or interface. They both work exactly the same when used. It is just in how they are defined that they differ.
I think types suit better with functional programming. I like that.