Convert JavaScript to TypeScript by combining prototype-based objects with class-based objects

My current challenge involves integrating JavaScript prototype with class-based programming. Here is an example of what I've tried:

function Cat(name) {
    this.name = name;
}
Cat.prototype.purr = function(){
    console.log(`${this.name} purr`);
}
Cat.prototype.meow = function(){
    console.log(`${this.name} meow`);
}


class Tiger extends Cat {
    constructor(name) {
        super(name);
    }

    meow() {
        console.log(`${this.name} roar`);
    }
}

Although the JavaScript code above is valid, I then attempted to convert the code to TypeScript as follows:

function Cat(this : any, name : string) {
    this.name = name;
}
Cat.prototype.purr = function(){
    console.log(`${this.name} purr`);
}
Cat.prototype.meow = function(){
    console.log(`${this.name} meow`);
}


// error: Type '(this: any, name: string) => void' is not a constructor function type.
class Tiger extends Cat {
    constructor(name : string) {
        super(name);
    }

    meow() {
        console.log(`${this.name} roar`);
    }
}

Unfortunately, the class Tiger does not accept the class Cat as its base class in TypeScript (valid in JavaScript but not in TypeScript). I am unable to change the Cat to standard class syntax because I need the .prototype access to point to another JavaScript library.

Can anyone assist in fixing the TypeScript code provided above? Perhaps by adding some .d.ts definitions.

Note: Adding // @ts-ignore would work, but I cannot do that as it would disable the VS Code IntelliSense feature.

Answer №1

One approach you could take is something along these lines:

interface DogClass {
  name: string
  bark(): void
  wagTail(): void

  new (name: string): DogClass
}

const Dog = function(this: DogClass, name: string) {
  this.name = name
} as unknown as DogClass
// Then simply add functions to the prototype and everything should function as expected

It's worth considering why you're opting for this method instead of just using a standard class. It's unclear how to properly type these function classes without resorting to the as unknown as DogClass workaround. It may be because this isn't a common practice, hence the lack of information on the topic. Just keep in mind that all classes ultimately get transpiled into functions.

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

React component with element style declared in module.css file and conditional state

I'm in the process of developing a mobile dropdown feature for a React web application. I am looking for guidance on the proper syntax to use when incorporating multiple classes into a React element. My goal is to apply styles from an imported module ...

React TypeScript with ForwardRef feature is causing an error: Property 'ref' is not found in type 'IntrinsicAttributes'

After spending a considerable amount of time grappling with typings and forwardRefs in React and TypeScript, I am really hoping someone can help clarify things for me. I am currently working on a DataList component that consists of three main parts: A Co ...

Utilize jQuery to interact with a Web API web service

Okay, so go ahead and roast me in 27 different languages if you want, but here's my dilemma: I've delved into creating a web service using the .NET 4 Web API. I've coded a method named GetTransaction that simply returns a string. It's ...

The Bootstrap 5 navigation bar does not extend to the full width of its parent

While working on a Bootstrap navigation inside a container, I encountered an issue where the navigation bar was not expanding to match the width of the container. It seemed like the padding had to be manually adjusted to fit properly. Below is the code sn ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Tips on resolving handlebars 'module not found' error in typescript while compiling to umd

In my client-side JavaScript library written in TypeScript, I am attempting to incorporate Handlebars. However, when I try to import using import * as Handlebars from 'handlebars', I encounter an error message stating that TypeScript "cannot find ...

It is imperative that the HTML div element remains within the boundaries of the page

Let me begin by providing some context. I am currently developing a responsive page that uses percentages to position my divs, allowing users to drag and drop items wherever they please. However, a problem arises when the user positions an object too close ...

Navigate to the following slide by clicking on BxSlider

Looking to enhance the navigation on my slideshow by using the slide itself as a next button, instead of relying on traditional prev/next controls. Although it seems like a simple feature to implement, I'm struggling to make it work. This is my curre ...

Cannot retrieve Global variables when using chrome.tabs.executescript in Chrome 55

After recently updating Chrome to version 55.0.2883.75, I encountered an issue with my self-developed Chrome Plugin used for parsing HTML files. In the plugin, I utilize chrome.tabs.executescript to retrieve data from a background HTML page. Previously, I ...

Error encountered while attempting to load an image in a React component using TypeScript linting

I am currently working on a React app with Next.js where I have imported an image using the following code: import image1 from '../../../img/dummy-image-2.jpg'; Subsequently, I use the image in my app like so: <img src={image1} alt="Dumm ...

Retrieve information from a database using PHP and assign it to a JavaScript variable

I need to display a Google map marker on my website, with the latitude and longitude values coming from the database in the columns labeled latitude and longitude. Here is the initial JavaScript code: var map; function initialize() { map = new GMaps( ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

Retrieve the webpage content (including any iframes) using a Firefox plugin

Hello there! I am currently working on retrieving data from a webpage that is updated using Javascript. Initially, I attempted to create a Java program to periodically fetch this page from the server, but the information was being updated too slowly. The ...

All the GET request methods are functional except for the final one. I wonder if I made a mistake somewhere?

After examining all the GET request methods, it appears that only the last one is not functioning properly. Despite attempting to log something to the console, no output is being displayed. router.get('/', function(req, res) { Golf.find({Year: ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

Retrieving entities from a text

I found a script on the Webdriver.io website that looks like this (adjusted for testing) const { remote } = require('webdriverio'); var assert = require('assert'); ;(async () => { const browser = await multiremote({ ...

Transform your scene into a stunning 3D texture using THREE.js's 3D Render Targets feature

After exploring the THREE.js example available here, I am curious about how to avoid scenes rendered as textures from appearing 'flattened'. Essentially, I want to maintain the depth illusion within the scene when using a WebGLRenderTarget. I ha ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

Having trouble with changing the state within an AngularJS (Ionic Framework) controller?

My goal is to switch views within the Search controller after receiving search results from the server through $http. However, my current approach doesn't seem to be working as intended. I also need to pass the response to the new view for displaying ...

React: "The function is not toISOString"

I am currently working on a Todo List project using Next.js. As part of the functionality, I am trying to implement a due date feature. However, when I make a post request, I encounter the following error: Unhandled Runtime Error TypeError: dueDate.toISOSt ...