DEV Community

Ayako yk
Ayako yk

Posted on

Polymorphism With TypeScript

To better understand classes in TypeScript, my book club members and I learned about object-oriented programming. I got stuck on polymorphism, so I did some research and created some classes on my own.

If you find any mistakes, I would appreciate it if you could point them out in the comments below.

  1. What is Polymorphism?
  2. What are some sample codes and which part demonstrates Polymorphism?

What is Polymorphism?
Polymorphism is one of the methods in Object-Oriented Programming. Polymorphism literally means "many forms."
When extending classes from a base class/parent class, you can modify the behavior of an existing method in the derived/child class.

Sample Codes

class Animals {
    animalName: string; 
    constructor(animalName: string) {
        this.animalName = animalName;
    }
    move(animalName: string = "Animals"):string {
        return `${animalName} can move.`
    }
}

class Fish extends Animals {
    constructor(animalName: string){
        super(animalName);
    }
    move(animalName: string): string {
      return `${animalName} swim.`
    }
}

class Birds extends Animals {
    constructor(animalName: string){
        super(animalName);
    }
    move(animalName: string): string {
      return `${animalName} fly.`
    }
}

class Kangaroos extends Animals {
  constructor(animalName: string){
    super(animalName);
  }
  move(): string {
    return `Kangaroos jump.`
  }
}


const animals = new Animals("")
const clownfish = new Fish("clownFish");
const sparrow = new Birds("sparrows");
const kangaroos = new Kangaroos("Kangaroos");

console.log(animals.move())
console.log(clownfish.move("Clownfish"))
console.log(sparrow.move("Sparrows"))
console.log(kangaroos.move())
Enter fullscreen mode Exit fullscreen mode

Polymorphism is demonstrated through the move() method, which can be modified in derived classes to provide different implementations. When you create a new object, it executes its own version of the move() method.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site