Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet:

class Salutation {
    message: string;
    constructor(text: string) {
        this.message = text;
    }
    greet() {
        return "Bonjour, " + this.message;
    }
}

class Greetings extends Salutation {
    constructor(text: string) {
        super(text);
    }
    greet() {
        return "Hola " + super.greet();
    }
}

let salutation = new Greetings("mundo");

console.log(salutation.greet()); // Hola Bonjour, mundo
console.log((<Salutation> salutation).greet()); // Hola Bonjour, mundo

The expectation is that the second log should display Bonjour, mundo. Upon inspecting the transpiled Javascript code, it appears to be an exact match which isn't surprising.

The real query lies in how you can cast the salutation object to its extended class.

Answer №1

When working with JavaScript (and TypeScript), methods are linked to a prototype that is connected to each specific instance, functioning similar to a virtual method table. Instead of calling a method based on the known type of an object, the function is retrieved from the prototype chain of the instance. This concept is reminiscent of C++ virtual methods.

Illustrated in code:

let person = new Individual('Alice');
// Expected behavior:
Individual.prototype.sayHello.call(person);
// Actual behavior in JS:
person.prototype.sayHello.call(person);

Answer №2

The greeter has already been successfully cast to its parent class.

Casting an overridden method as its parent class does not alter its behavior.

Answer №3

My perspective on casting is that it should not be viewed as a "convert into" action, but rather as an "interpret as" operation. By providing the compiler with a hint regarding the type or interface being dealt with, casting establishes the available properties and methods associated with that type or interface. It does not define the specific implementation of these methods; instead, it focuses solely on their signature (identifying the input and output types).

Answer №4

When you use casting in code, you are essentially telling the compiler to treat a variable as if it has a specific type as its value.

Casting doesn't actually change the JavaScript code itself, but rather helps prevent errors by indicating how a variable should be interpreted. The JavaScript language itself doesn't have strict types.

One interesting aspect of inheritance is that when a class instance has a property with the same name as a property in its prototype (base class), the instance property takes precedence. This means that the function called will always be the one defined directly on the specific instance.

To fully understand how this works, it's helpful to examine the output code and apply your knowledge of prototypical inheritance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining NodeJs with Mysql for multiple queries using a chained method

Hey everyone, I'm struggling with running mysql queries repeatedly in my Node.js application. I need to shape the second query based on the results of the first one. The code example I have below is not working as expected. Can anyone provide guidance ...

I am looking for guidance on removing the bottom line from the ionic 4 segment indicator. Any advice or tips on

.segment-button-indicator { -ms-flex-item-align: end; align-self: flex-end; width: 100%; height: 2px; background-color: var(--indicator-color); opacity: 1; } I am a beginner in hybrid app development and ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

Steps for moving data from a JavaScript variable to a Python file within a Django project

I have created a unique recipe generator website that displays each ingredient as an image within a div. When the div is clicked, it changes color. My goal is to compile the ids of all selected divs into one array when the submit button is clicked. I have ...

Using jquery to dynamically retrieve the unique property identifier

I have a dynamically generated table with a button labeled as view images. Each time this button is clicked, I need to retrieve the image names from the database for that specific property. <?php foreach($unapproved as $unapp):?> < ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

Is it possible to install a Chrome extension specifically for YouTube on Google Chrome?

Hey, I'm trying to eliminate thumbnail images from YouTube. The code I am currently using is: while (true) { $("ytd-thumbnail").remove() } As of now, when I input this code in the console, it successfully removes all thumbnail images. However, I ...

The Angular controller fails to execute upon startup in the Ionic app

As a newbie to the Ionic Mobile Framework and Angular JS, I'm working on a login page for the first time. My goal is to navigate to the homepage only if the session has not expired when the login page launches. If the session has expired, then it shou ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

Ensure the inferred type is asserted in TypeScript

Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method: function assertType<T>(value: T) { /* no op */ } assertType<SomeType>(someValue); This technique prov ...

Timeout for jQuery animations

My jQuery animation script is causing an issue where it does not finish the animation before returning to the parent function. Specifically, the JavaScript code changes a background color, calls the animate function, the animation starts but doesn't c ...

Can the arrangement of icons/buttons on the JW Player control bar be customized?

I am trying to customize the skin of my JWplayer like this: This is my current progress: I have been researching how to rearrange the order of icon / button on the controlbar. According to the jwplayer documentation, the buttons on the controlbar are div ...

Troubleshooting Problems with Ajax across Different Web Browsers

I am facing an issue with my ajax function - it works perfectly on Chrome and Firefox, but not on Internet Explorer 8. Can anyone help me identify the problem? Here is the HTML section: <select id='choices'> <option id="no" value="no" ...

Angular single page application with a sleek, user-friendly navigation bar for easy browsing

I have been attempting to solve the issue at hand without much success. As a newcomer to web development, I have been working on creating a basic app using angularjs and bootstrap. My pages are fairly sparse, consisting only of a few inputs and buttons t ...

Capturing groups in Javascript Regex not populating back-references correctly

Here's an interesting situation (or maybe not so uncommon): I'm trying to extract two specific capturing groups using JavaScript regex. The first group should consist of one or more digits (0-9), while the second group should consist of one or mo ...

Error in Jest Testing: An unexpected character '@' was encountered

Encountering issues with NuxtJS Jest tests and attempting to build a Nuxt app to test URL's due to route name errors in some components. Here is the code snippet I tried: beforeAll(async () => { nuxt = new Nuxt({ ...config, server: { port: 3001 } ...

Encountered an issue connecting Firebase with NextJs during build process

Recently delving into NextJS, I successfully created a project using Firebase. However, upon running "npm run build," an error has surfaced: @firebase/firestore: Firestore (X.X.X): Could not establish connection with Cloud Firestore backend. Backend faile ...

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

How can I stop and hover over time in AngularJs Interval?

Within my UI, I have a time element that is continuously updated using AngularJS Interval. Even the milliseconds are constantly running. Is it possible to implement a feature where the time pauses when hovering over it? Any assistance would be greatly appr ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...