Why is there a mismatch between the Typescript interface and implementation constructor signature?

What is the reason for the discrepancy between the constructor signature and interface declaration in the code snippet below, and how can it be rephrased? The reported error is

'Class 'Item' incorrectly implements interface 'ItemClass'. Type 'Item' provides no match for the signature 'new (Scope?: Scope | undefined): Item'.'

The purpose of this code is to provide factory support for subclasses identified at runtime by a string name obtained from a class serialization. The abstract AsyncCtor defines and initializes a Ready property. I could achieve this directly in

export interface ItemClass {
  Ready: Promise<any>;
  new(Scope?: Scope): Item;
}

export abstract class AsyncCtor {
  public Ready: Promise<any> = new Promise((resolve, reject) => resolve(undefined));
}

export abstract class Item extends AsyncCtor implements ItemClass {
  static Type: Map<string, ItemClass> = new Map<string, ItemClass>();
  static register(typeName: string, typeClass: ItemClass): void {
    this.Type.set(typeName, typeClass);
  }
  public static new(raw: any): Item {
    let graph = typeof raw === "string" ? JSON.parse(raw) : raw;
    let typeClass = Item.Type.get(graph.Type) as ItemClass;
    let item = new typeClass();
    ...
    return item;
  }
  constructor(public Scope?: Scope) {
    super();
  }
}

If I remove the explicit declaration that Item implements ItemClass, everything compiles successfully and the Item.new(raw) method functions properly, indicating that it does indeed implement ItemClass.

Despite trying

  constructor(public Scope?: Scope | undefined) {

Answer №1

There seems to be a mix of static class methods and instance methods in your code.

A better structured version could be:

type ItemClassConstructor = {
    new (Scope?: Scope): Item;
    create(raw: any): Item;
}

interface ItemClass {
    Ready: Promise<any>;
}

abstract class Item extends AsyncCtor implements ItemClass {
    static Type: Map<string, ItemClassConstructor> = new Map<string, ItemClassConstructor>();
    static register(typeName: string, typeClass: ItemClassConstructor): void {
        this.Type.set(typeName, typeClass);
    }

    public static create(raw: any): Item {
        let graph = typeof raw === "string" ? JSON.parse(raw) : raw;
        let typeClass = Item.Type.get(graph.Type);
        let item = new typeClass();

        return item;
    }

    constructor(public Scope?: Scope) {
        super();
    }
}

(Check the code in playground)

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

Increase the size of the NativeScript switch component

Here is the code I am working with: .HTML <Switch style="margin-top: 10" (checkedChange)="onFirstChecked1($event)" row="0" col="1" horizontalAlignment="center" class="m-15 firstSwitchStyle"></Switch> .CSS .firstSwitchStyle{ width: 30%; ...

Tips for using conditional rendering with React and TypeScript

Issue with Conditional Rendering in TypeScript It seems like I might have encountered a problem with the way I declare my components. Take a look at this TypeScript snippet: import React, { FunctionComponent } from 'react'; export const Chapte ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

TypeScript excels in typechecking when using two individual assignments, but may encounter issues when attempting typechecking with tuple

I am quite puzzled by a discovery I made and I am seeking to understand why TypeScript is displaying this behavior and what the underlying reason may be. Here is the code snippet: class A { constructor(public name : String, public x = 0, public y = 0) ...

What is the proper way to create a child JSON object in Angular using TypeScript?

I have a model.ts file. export class MainClass { someVar: string; var2: string; subClass: SubClass; contact: ContactList; } export class SubClass { subItem: { item1: string; item2: string; item3: string; } constructor() ...

The `message` binding element is assumed to have a type of `any` by default

I am trying to send data from parent component to child component, but I am encountering an error: Binding element 'message' implicitly has an 'any' type. Can someone assist me with my code? const Forms = () => { const [messageTe ...

When using Visual Studio Code debugger on a React project with TypeScript, breakpoints are not being triggered

I've been utilizing the Debugger tool in VS Code and my launch.json settings are set up as shown below: https://i.sstatic.net/dj3Qs.png However, despite adding breakpoints to my code, it doesn't halt there. Is there a specific configuration need ...

NativeScript: TypeScript for Formatting Numbers

Being a beginner in NativeScript, I'm finding it difficult to find basic information through Google search. But now, I have a specific question: I have the number 1234567.89 stored in a variable, and I want to display it in a label with the format ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

What steps should I take to address conflicting type identifiers between Cypress and jQuery?

Currently, I am tasked with writing TypeScript end-to-end tests for an Angular 11 application. Following the recommended practices of Cypress, my test setup is encountering a conflict due to existing jQuery dependencies (3.5.1) in the app and Cypress (8.4. ...

Confidential inheritance and initialization methods

I am facing the following challenge: I want to inherit a class as protected (without needing any member or function from the base class outside of the derived class) I want to find a way to access the base constructor Here is an example which results in ...

Championing React, TypeScript, and TSLint: A Pose of Cur

In my React and TypeScript project, I am utilizing react router dom to dynamically load components from the backend. However, when I import components like "ListData", they are considered unused and removed when I save. How can I keep these components fr ...

amChartv5 on Angular is successfully displaying a Gantt chart that includes multiple categories with the same name being resolved

I've been working on integrating an amCharts v5 gantt chart with Angular 13. Each bar in the chart represents a project, and if there are multiple occurrences of a category, they should stack like a timeline. I've successfully retrieved data from ...

Utilize the authenticated page across various tests in Playwright for efficient testing

Starting out fresh with playwright and node.js frameworks Currently in the process of developing a framework using playwright with typescript. Everything was smooth sailing until I reached the point where I needed to run my tests sequentially on the same ...

Leveraging Generics in TypeScript for Creating a Versatile React Component

I developed a versatile React Component that includes several Props capable of accepting a Generic data type. Below is the component in question: export interface MappedObject { key: string; name: string; type: string; status: AppStatus; } export ...

Guide to integrating global interfaces into your Nuxt project

Recently diving into the world of Nuxt 3, I've encountered a challenge while exploring TypeScript functionalities. My current goal is to create a versatile NavBar featuring multiple buttons with unique links. To achieve this, I aimed to establish an ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

Implementing a spread operator in React.js with TypeScript to add the final element only

I'm currently facing an issue with adding an element to an array in react.js this.state.chat_list.map(elem => { if ( elem.name .toLowerCase() .indexOf(this.props.searching_username.toLowerCase()) !== -1 ) { this.setState( ...

A TypeScript class that is a concrete implementation of a generic type

When handling a login operation, I receive an HTTP response like this: interface ILoginResponse { // ok message: string token: string; } This response structure is part of a generic response format that I intend to use for all my HTTP responses: i ...