While working with Typescript we have ever thought that if type and interface works the same then why we have 2 options? Why we need type or interf...
For further actions, you may consider blocking this person and/or reporting abuse
There are actually more differences between
interface
andtype
keywords.Pros of using
interface
s overtype
s:Interface
s provide better error messages. You can verify this by checking lines 48-49 of the example;Interface
s are extended withextends
keyword. That comes in handy when there are conflicting fields in the objects you are trying to merge. As extendingtype
with&
keyword would not inform you about conflicting fields and also would set typenever
for conflicting fields. At the same time extendinginterface
withextends
keyword would inform you that provided types cannot be simultaneously extended. You can see an example of this behavior here.So as a rule of thumb in our project we use
interface
s overtype
s when possible. Also we have aESLint
rule that helps us with this. It makes developers useinterface
keyword overtype
keyword whenever it possible.P.S.
Also I'm not sure about the second point of the article. The given code works fine with both
interface
andtype
keywords.Interface is definitely have their place, but there's a ton of stuff you can't do with them. There's also no restriction on using one or the other. The type of a property in an interface can be a computed type that itself is not an interface.
We use them quite heavily in JSON structures that allow us to create static metadata without having to a ton of runtime checking except entry and exit points. What's inside the system we know that they correspond to our various complex type rules.
Fantastic! I did not know about type computed properties! Thanks!!
@icolomina !!
I'm delighted that my writing has benefited you!
Super Informative !!
How if I want key not needed if other key has value like
How to do that?
Typescript is statically typed. Types are not conditional. You can look into type state pattern, but it is complex and more code in typescript. Rust has a cleaner implementation without complexity and duplication.
Another option is to make
keyOne
as a union.Last option I can think of is using generics and infer.
You can archive this with types pretty easily.
Not sure if the syntax is 100% correct, I wrote this on my phone 😁
@Web
It's my pleasure that it will enhance your knowledge !!
doesn't the last property count as a computed property?
That's not a computed property. The author is confused. The thing you can do in types that you can't do an interfaces is things like: