Implementing Interfaces in TypeScript with Classes
The syntax keyword for ensuring classes adhere to a specific interface is implements
:
class Shape implements IShape { // ...}
Now if we were to add a property to IShape
, an error would be thrown at the Shape
class for not correctly implementing the interface IShape
:
``
Transcript
00:00 Okay, the syntax here is class shape implements I shape. Ooh, interesting. Class shape implements I shape. Now I shape, what we can do is if we add a property to I shape up here, and let's say we add a property, ooh, I don't know, like, let's just say something, which is going to be a string, or maybe even ID,
00:20 let's say a string. Now we're going to get an error on shape saying class shape incorrectly implements interface I shape. That's funny, even though I shape is actually a type, not an interface, but property ID is missing in type shape, but required in type I shape. Okay, so we would have to say ID equals one,
00:40 for instance, or A. Now this means then that we've kind of like saying to our class, you need to implement this particular type. This particular set of things needs to be on your public API. Note that it doesn't count for private stuff here, so we don't need to mention X and Y on here.
00:57 It's really just for things that you want your public class or the public interface of your class to be able to be accessed. So this is really nice and a cool little piece of syntax, and you notice that the naming convention here is kind of interesting. We're using some what's called Hungarian notation, which is what we have the class,
01:16 which is kind of like the object, and then we say I shape or T shape, for instance, which is kind of like saying this is the interface that describes this class, and that's the kind of relationship between them. You don't necessarily need to do this. We can kind of use class as a type, really, which is kind of fun.
01:35 So we can say if something needs to receive a shape, we don't need to pass in I shape and implement all that. We can just say this function receives a shape. Very nice. If I just show you that, we can say const func equals a little function, and the shape has to be a shape like that. Very cool. So we don't need this kind of implement stuff,
01:54 but sometimes it's useful, and sometimes it just means that you can declare a type, for instance, and then say every single instance of this class declaration, for instance, so let's say a triangle needs to implement I shape, a square needs to implement I shape, then it means that you can just be really, really strict about the way that you declare your classes.
02:13 Quite useful.