4

Polymorphism in TypeScript (OOP)

 2 years ago
source link: https://blog.bitsrc.io/polymorphism-in-typescript-oop-17646dcda307
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Polymorphism in TypeScript (OOP)

In today's article, I want to talk about Polymorphism in TypeScript, which is one of four pillars of object-orientated programming.

Photo by Arnold Francisca on Unsplash

What is Polymorphism?

Polymorphism is the ability to create a class that has more than one form. Or in other words, classes have the same methods but different implementations.

Example

So, before explaining how polymorphism works, I better show you, how it does not work by an example.

Imagine we have two animal classes, one class is called Dog, the other class is called Cat. Both classes should have the same properties and methods.

bad way

And that works fine, but actually, that is not the way to go. As I said, both classes have the exact same properties and methods, so it makes sense to inherit this from a parent class.

Let’s have a look at a better way:

good way

The results of the makeSound methods are exactly the same, but the approach is a little bit different.

Thanks for reading my article about Polypmorphism in TypeScript. I hope, I could refresh your knowledge with this quick example.

Cheers

Use any component in all your projects

Up until now, you used to build features hidden inside larger projects.

But what if you were to develop independent features first, and then easily compose and manage them in many applications? Your development will become faster, more consistent, and more scalable every day. Create a component once, and truly use it anywhere to build anything.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing them to applications. You can start small with a nice project, some shared components, or even trying out Micro Frontends. Give it a try →

0*hX30HLO0QBJky-kT?q=20
polymorphism-in-typescript-oop-17646dcda307
An independent product component: watch the auto-generated dependency graph

Learn more


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK