Transcript:
Hello everybody!
In this video I wanted to share a quick TypeScript tip with you. And that tip is that you can create interfaces based off of classes.
Here in front of me I have some code from a game I’m working on.
Don’t worry about the details just focus on line 410 where we have interface ShapeGenerator extending Generator.
Nothing too exciting there if you’ve already seen my video on interfaces, but if we jump to the definition of Generator… You’ll see that it’s a class and not an interface!
It turns out that TypeScript will let you create interfaces from classes, and it does this in an intuitive way: All the public class fields and methods become part of your interface. And then, of course, you can add more if you need them.
Now, why would you want to create an interface in this way?
Well, for this program in particular, I have a number of classes that are based on Generator, but they are all completely separate in their implementation. However, some of them share these three fields, and I want to be able to do things like create arrays of ShapeGenerators.
Create a new interface based off of the Generator class is a super easy way of making it so that I don’t have to repeat all the fields of Generator, and I don’t have to add any extra levels of inheritance just to be able to treat all my similar classes in similar ways.
You won’t need it all the time, but in cases like this, it’s helpful to know that this feature is there.
That’s it for now.
If you want to dive deeper into TypeScript, I’m working on a course called Learn TypeScript by Example. You can find it at https://typescriptbyexample.com/ If you scroll down to the bottom you can put in your email address and I’ll let you know when the course is released.
Thank you so much for watching! I will see you in the next video.
Learn TypeScript #6, Advanced Classes