Creating a Simple Typescript Polymorphism Logger

java-polymorphism-featured-image-1280x720.pngIf you are coming from a Java or C# background you are familiar with the idea that an object that implements an IAnimal interface can be a Dog or Cat. That’s Polymorphism.

In this Typescript tutorial, I’ll show you how to use this, simply, to have your app write out to the console a log or error message.

First, let’s define our object to be a function that expects a message and returns nothing.

let logger: (message: string) => void;

Now let’s create that “Dog and Cat” implementation. One to output errors and one for messages.

Notice how the interface of the functions matches the logger we defined above:

function error(message: string): void {
  console.error(message);
}

function log(message: string): void {
  console.log(message);
}

We can now assign the logger to be a log or error function depending on the input. If the age is more than 5 then we log, else we error out.

let age: number = 5;
if (age>5) {
   logger = log; 
} else {
   logger = error;
}

logger(`${age} was the age`);

In the console of the browser we see:

2019-10-18 15_12_52-https___localhost_44351.png

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s