Dealing with the error message "The 'new' keyword requires a constructor signature when targeting a type that does not have one, resulting in an implicit 'any' type.ts(7009)"

Currently, I am in the process of migrating an outdated JavaScript library to TypeScript for integration into Vue 3. However, I encountered an error message that states: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009). It seems like the issue stems from this particular code snippet within my package, yet the solution still eludes me. Below is the problematic code:

function Media(this: any, options: any ) {       
    this.clientOptions = options || {};
    this.apiVersion = this.clientOptions.version || 'v1';
    this.baseURL = `${this.clientOptions.server}/${this.apiVersion}`;
    this.token = this.clientOptions.token || null;
    this.files = null;
    this.endpoints = this.clientOptions.endpoints || {
        upload: 'files/upload',
        chunk: 'files/upload/chunk',
        auth: 'auth',
        youtubeDownload: 'youtubes/download',
        facebookDownload: 'facebooks/download'
    };
    this.chunkPhase = 'start';
    this.chunks = [];
    this.chunkActive = [];
    this.chunkStartOffset = 0;
    this.chunkMaxActive = this.clientOptions.maxActiveChunk || 3;
    this.chunkMaxRetries = 1;
    this.fileSize = 0;
    this.chunkFile = null;
    this.chunkSize = null;
    this.chunkSessionId = null;
}
Media.prototype = {
    getToken: async function () {
        var self = this;
        try {
            var assignUrl = `${self.baseURL}/${self.endpoints.auth}`;
            var data = {
                'username': self.clientOptions.user.username,
                'password': self.clientOptions.user.password
            };
            const response = await self._postx(assignUrl, data);
            if (response.data && response.data.access_token) {
                self.token = response.data.access_token;
            }
            return self.token;
        } catch (error) {
            return error;
        }
    },
}

...

Furthermore, here is the usage of the code in Vue which triggers the aforementioned error message:

import media from 'mediaLibrary'
const m3 = new Media(
  {
    server: 'myServer',
    user: {
        username: 'myUserName',
        password: 'abc123'
    },
    version: 'v2',
    endpoints: {
        upload: 'files/upload',
        chunk: 'files/upload/chunk',
        auth: 'users/signin',
        youtubeDownload: 'youtubes/download',
        facebookDownload: 'facebooks/download'
    } 
});

I am hopeful that there exists a resolution to assist me in rectifying this issue...

Answer №1

If you encounter this issue while using the `new` keyword with a constructor-function in TypeScript, fret not as it is a common problem with two possible solutions:

1. Convert the constructor function into a class. Here's an example:

function Employee(fullName: string, salary: number) {
  this.fullName = fullName;
  this.salary = salary;

  this.getSalary = function () {
    return this.salary;
  };
}

To

class Employee {
  constructor(public fullName: string, public salary: number) {
    this.fullName = fullName;
    this.salary = salary;
  }

  getSalary() {
    return this.salary;
  }
}¨

2. Impose the type (a workaround). For cases where editing the class directly is not possible, this hacky solution can be employed although it may not have long-term support:

function Employee(this: any, fullName: string, salary: number) {
  this.fullName = fullName;
  this.salary = salary;

  this.getSalary = function () {
    return this.salary;
  };
}

const emp1 = new (Employee as any)('James Doe', 100);

In your specific scenario, it would look like this:

const m3 = new (m3dia as any)(
  {
    server: 'myServer',
    user: {
        username: 'myUserNamw',
        password: 'abc123'
    },
    version: 'v2',
    endpoints: {
        upload: 'files/upload',
        chunk: 'files/upload/chunk',
        auth: 'users/signin',
        youtubeDownload: 'youtubes/download',
        facebookDownload: 'facebooks/download'
    } 
});

(3. Remember, you can also choose to ignore TypeScript related errors using //@ts-ignore)

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

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

"Exploring the use of TypeScript in React higher order components

Check out this article for a detailed explanation of HOC: https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb Here is the code I have written using HOC: import * as React from 'react'; import Dropzone f ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

The issue of Vue js Computed property failing to update upon changing route

On my dashboard page, I encounter an issue where my computed property giveaways does not update when navigating back to the page from other links. The data retrieval works fine on page refresh but fails to update the computed property upon returning. Despi ...

Retrieving the default props of a child component in Vue after it has mounted

I'm currently exploring how to access the default properties (props) for a child component. The scenario involves two components, A and B. Component B wraps around component A, which is passed properties. My goal is to determine the default values of ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...

Generate dynamic property values based on calculations

I am facing a challenge with a form that I have designed. Could you guide me on how to dynamically update the value of the calculate field (contingency) whenever the user modifies the values of budget1 and budget2? I have attempted several approaches witho ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

When the affirmative button is clicked, apply a border and background color

I am in the process of creating custom text boxes for user comments. I need help with adding borders and background colors to a box when the user clicks on the YES button, in order to visually indicate which box the click originated from. Can anyone assis ...

What is the reason behind VueJs not having built-in support for multiple select options?

Recently delving into the world of vue, I encountered a challenge while working on an update form. When trying to pre-select multiple options using the selected attribute, I noticed that only the last option was being selected. Upon further investigation, ...

What is the best way to transfer data to a component that is not directly related

I am looking to showcase an image, title, and description for a specific recipe that I select. Here is my setup using ItemSwiper (parent): <template> <Slide v-for="recipe in storeRecipe.data" :key="recipe.rec ...

What is the best way to retrieve the `any` type when utilizing the `keyof` keyword?

I am struggling to articulate this question properly, so please refer to the code below interface TestParams<T> { order?: keyof T attr1?: number attr2?: string } async function Test<T = any>(_obj: TestParams<T>): Promise<T> { ...

Documentation for npm package that has been published

Recently, I created my very first npm package using TypeScript. However, when I tried to use this package in another project, I realized that I wasn't getting the expected code completion and it was challenging to work with it without proper support. ...

You can activate Lightgallery just one time in VueJs

I am facing an issue where lightgallery can only be opened once. Subsequent clicks on the button are unresponsive. The lightgallery is being used as a component. Within my parent component, I have two buttons for opening image or video gallery ParentComp ...

What is the appropriate event type to pass to the onKeyPressed function in a React application utilizing MaterialUI and written with Typescript?

I am currently working on a React application using Typescript and MaterialUI, where I have implemented a TextField component. My goal is to capture the value of the input HTML element when the user presses the enter key. To achieve this, I have created ...

The specified 'IArguments' type does not qualify as an array type

Currently working on crafting a personalized logger. It's a fairly straightforward process, but I'm running into some errors that are muddying up my output. Here's what I have so far: @Injectable() export class Logger { log(...args: any ...

Vue js parent-child communication using event bus fails to function

Is there any way to successfully communicate between non parent child components in vue js document? I followed the instructions in the vue document, but unfortunately, my code did not work as expected. Below is a snippet of my code: The structure of the ...

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

Steps for deploying a Vue JS website to an Ubuntu based VPS

I currently have a VPS running on Linux Ubuntu with two websites and two corresponding domain names. One of my websites, trail-notes.tk, is successfully deployed and running on the server without any port configurations in the config file. The issue arises ...

The 'current' in react typescript is not found within the type 'never'

Currently, I am working with react and typescript in my project. To fetch the height of a specific div tag, I decided to utilize useRef method. However, when trying to access 'current' property, TypeScript throws an error. Property 'current& ...