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

Angular/Typescript: develop a factory function that creates objects based on the parent class's properties

I'm currently working on implementing a factory method that can return classes dynamically, and here's my code snippet: getWidget<T extends WidgetBase>(componentName: string): Type<T> { switch (componentName) { default: ...

Safari is capable of rendering Jquery, whereas Chrome seems to have trouble

The code I am using renders perfectly in Safari but not in Chrome. Despite checking the console in Chrome, no errors are showing up. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="ht ...

Upload the PDF file along with other form data in a React application

I'm currently facing an issue with using formData for submitting a pdf file const [file,setFile] = useState() const [isFilePicked, setIsFilePicked] = useState(false); I have an input of type file <input accept=".pdf" type="file&quo ...

Can I utilize p5.Vector.fromAngle() in Vue JS?

Incorporating P5 into a Vue application can be achieved using the following code snippet: let script = p5 => { p5.setup = _ => { this.setup(p5) } p5.draw = _ => { this.draw(p5) } } this.ps = new P5(script) While functions like ba ...

Navigate a first person simulation using three.js and control your movements with the keyboard arrow

To access my reference material, please go to http://jsfiddle.net/fYtwf/ Overview I am working on a basic 3D simulation using three.js where the camera is surrounded by cubes in three dimensions. These cubes serve as a visual guide to where the camera is ...

Mobile Chrome allows users to utilize the IFrame player API for enhanced video

Currently, I am working on creating a mobile website where I plan to include some YouTube videos using the IFrame player API (https://developers.google.com/youtube/iframe_api_reference). My main goal is to have the video start playing only after the user ...

javascript with python

Currently, I'm in the process of parsing a html page. I've experimented with spynner, selenium, and mechanize, however none of them have been effective when dealing with JavaScript in this particular scenario. Is there anyone who can provide som ...

I am facing difficulties with the header in CSS as it is not resizing properly

I'm having trouble getting my mobile-first design to work properly because the header doesn't resize in mobile view. I'm satisfied with how it looks in full-screen, but I haven't been able to make any media queries work. You can downloa ...

Sending back the requested information in C to the ajax (jquery) CGI

After fetching specific data using C in my jQuery, how can I appropriately transfer the data to C? function Run() { $.ajaxSetup({ cache: false }); var obj = {"method":"pref-get","arguments":{"infos":["sys_info"]}}; alert("Post Json:" + JSO ...

What's the best way to utilize the tsconfig.json "types" field within a monorepository setting?

Part 1 - Utilizing the "types" Field When a TypeScript library like library A provides type definitions alongside its normal exports, it looks like this: declare global { function someGlobalFunction(): void; } Library B depends on the type definitions ...

Encountered a SyntaxError stating 'Unable to use import statement outside a module' while attempting to utilize three.js

I'm facing difficulties with incorporating three.js into my project. Initially, I executed: I am referring to the guidelines provided here: In my VS Code terminal for the project folder, I ran the following command: npm install --save three Subsequ ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Unable to execute ajax on dom ready in Internet Explorer 9

Here is some code that needs to be executed on DOM ready without any user interaction: if($.browser.msie){ console.log("Using getJSON"); $.getJSON(baseUrl,function(){ alert('hi'); }); }else{ setTimeou ...

In JavaScript, a prompt is used to request the user to input a CSS property. If the input is incorrect,

Implement a while loop that continuously prompts the user to enter a color. If the color entered matches a CSS property such as blue, red, or #000000: The background will change accordingly, but if the user enters an incorrect color, a message will be dis ...

Importing components with local data within an ngFor in Angular TypeScript

Having recently started working with Angular2, I am facing a challenge with importing components in ngFor loops. The issue seems to arise when importing components with data in ngFor loops; it checks for values in the .ts file instead of the local variabl ...

Using a template literal as a prop is causing rendering issues

I have a functional component const CustomParagraph = forwardRef((ref: any) => { return ( <div> <p dangerouslySetInnerHTML={{ __html: props.text }}></p> </div> ); }); Whenever I use this component, I am unable ...

React: Retrieved information, yet unable to access the properties of the object

After successfully fetching data from an API call and seeing the results in console, I am facing issues with accessing object properties and displaying them. interface Data { data: [] isLoading: boolean } function About() { const [ dataUser, ...

When trying to console log a selected date, the output displays as undefined

<div class='col-sm-6'> <input [(ngModel)]="date" id="date" name="date" class="form-control" required/> </div> $(function () { $('#date').datetimepicker({ format: 'DD/MM/YYYY hh:mm' } ...

What is the solution to the error message that states a bind message provides 4 parameters, while a prepared statement "" necessitates 5?

Is there a way to fix the issue where the bind message provides 4 parameters but the prepared statement "" requires 5? I've tried solutions from others who faced similar problems without success. (I've included all classes for better error unders ...

Recreating elements in ng-repeat using ng-click conditionally

I am attempting to swap an anchor tag with an image when clicked by the user. The code snippet I'm using looks like this: <div ng-repeat="postpart in currentPost.parts "> <div ng-if = "!postpart.isclicked"> <img ng-src= ...