2. Inheritance in TypeScript Flashcards
How do you enforce a class to extend another class in TypeScript?
By using the extends
keyword on a new class to give it a base class.
eg. class Dog extends Animal { //…
How do you extend the functionality or data of a base class from a derived class?
By simply declaring new methods or properties for the derived class. The derived class will then inherit all the functionality and data of the base class but also provide the additional ones defined in it.
How do you enforce a class to implement another class in TypeScript?
By using the implements
keyword.
eg class aClass implements anotherClass { //…
What’s the difference between extending and implementing a class?
Extending a base class from a derived class means that there is a direct inheritance from the former to the latter, meaning that it adopts its methods and properties. Implementing, on the other hand, only ensures that the base class’s “shape” is implemented on the derived class. Meaning it has the same properties/methods as its base class, but it implements them itself rather than adopting them.
In other words, extends
defines a “child” whereas implements
enforces shape.
How does a derived class reference its base class?
By using the super
keyword within its constructor or methods.
How do you determine whether an object is derived from a given base class?
By using the instanceof
keyword.
eg. dog instanceof animal;
Is a class that implements another an instance of the class it implements?
No.
Is a class that extends another an instance of the class it extends?
Yes.
How does a derived class use the constructor of its base class?
By using the super
keyword with parentheses and passing it the parameters that the base class constructor requires.
eg. super(“alican”, “demirtas”);
How do you access a base class’s methods from its derived classes?
By dotting into the super
keyword and calling the method.
eg. super.meow();
What happens when a derived class overrides a base class’s method and then tries to use that method by dotting into the super
keyword?
It calls its own method rather than the base class’s unless it’s in the method definition that overrides the same-named method. This is because once you override something, it’s permanent.
Should you use any
over generics or is it the other way around?
The other way around. Generics are a much more robust approach to giving static typing to a dynamic type.
How do you make a class generic in TypeScript?
By using angle brackets to define a type parameter. Once this is done, we can use that type all over the class.
eg. class User { classicUserData:T; ...
What is method/parameter overriding?
It’s when a child class overrides its parent class’s methods.
How do you overload a method in TypeScript?
You can’t. You can only override it using the exact same parameters that the base method has. One way to work around this, though, is to have optional parameters.
eg. public hasAccess(user:User = undefined) { //...