Why Mixin Class inference is not supported in Typescript

I encountered an issue in my code: The error message 'Property 'debug' does not exist on type 'HardToDebugUser'.' was displayed. It seems like Typescript failed to infer the mixin class correctly. Can you please explain this to me? Thank you!

type ClassConstructor<T> = new(...args: any[]) => T
function withEzDebug<C extends ClassConstructor<{
    getDebugValue(): object
}>>(Class: C) : C{
    type Hi = typeof Class;

    return class extends Class {
        constructor(...args: any[]) {
            super(...args)
        }
        debug() {
            let Name = Class.constructor.name
            let value = this.getDebugValue()
            return Name + '(' + JSON.stringify(value) + ')'
        }
    }
}
class HardToDebugUser {

    constructor(private name: string, private grade: number) {
        this.name = name;
        this.grade = grade;
    }

    getDebugValue() {
        return {
            name: this.name,
            grade: this.grade
        }
    }
}
let User = withEzDebug(HardToDebugUser);
let userWithDebug = new User("hi", 1);
userWithDebug.debug();

Can you provide guidance on how to correctly infer a mixin class in Typescript.

Answer №1

The function called withEzDebug explicitly specifies that its return type is C, which is the same type as the class passed in. It does not add anything to C, just returns C. And TypeScript follows this specification.

If you prefer the return type to be inferred from the anonymous class, simply remove the return type annotation (I have also taken out the unused Hi type [which was essentially C] :-) ):

type ClassConstructor<T> = new (...args: any[]) => T;

function withEzDebug<
    C extends ClassConstructor<{
        getDebugValue(): object;
    }>
>(Class: C)/* >>>No return type annotation here<<< */ {
    return class extends Class {
        constructor(...args: any[]) {
            super(...args);
        }
        debug() {
            let Name = Class.constructor.name;
            let value = this.getDebugValue();
            return Name + "(" + JSON.stringify(value) + ")";
        }
    };
}

class HardToDebugUser {
    constructor(private name: string, private grade: number) {
        this.name = name;
        this.grade = grade;
    }

    getDebugValue() {
        return {
            name: this.name,
            grade: this.grade,
        };
    }
}
let User = withEzDebug(HardToDebugUser);
let userWithDebug = new User("hi", 1);
userWithDebug.debug();

Playground link

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

Is it possible to pass parameters from a base class's constructor to a child class?

I'm facing an issue with my base (generic) classes where the properties are initialized in the constructor. Whenever I try to extend these classes to create more specific ones, I find myself repeating the same parameters from the base class's con ...

Using TypeScript arrow function parentheses in the filter function

If I have an array of movie objects like this: const movies: Movie[] = [ movie1, movie2, movie3, movie4 ]; And if I want to remove a specific movie from the array, such as movie2, I can use the following code: movies = movies.filter( m => m !== ...

The type of the object is classified as 'unknown' (2571) while utilizing the map() function with an array containing objects

After researching this error extensively on Google and reading multiple posts, I am still unable to find a solution. I am trying to fetch data from an external API call that has the following signature: const properties: { [x: string]: unknown;} | { [x: s ...

What steps should I take to enable the camera view in ngx-scanner?

I am currently working on an app that utilizes a QR code scanner. To implement this, I am using the ngx-scanner component, which is a modified version of Google's ZXing scanning library designed for Angular. However, I am encountering an issue where ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

The successful operation of 'Ionic serve --lab' may involve the need to manually save the app.module

We are currently working on an Ionic project that consists of several pages and a single custom provider named request.ts. The issue we are facing is that whenever we launch it using the command ionic serve --lab, the compilation fails (with the error poin ...

Is it possible to assign an interface to an object property in TypeScript?

I am currently working with an object that looks like this: export class Section{ singleLabel:string; pluralLabel:string; index:number; dataInterface:Interface; } My goal is to assign an interface to the dataInterface field, as I need to use the S ...

getting TypeScript configured with webpack

I am currently using Typescript to develop a back-end API utilizing graphql and express. To manage the project development and building process, I have implemented webpack. As part of my setup, I am employing raw-loader in order to load graphql schemas an ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

Ways to trigger child components function from parent component

I am working with a parent-child component setup. In the child component (child.component.ts), there is a method called "childFunction()". Now, I need to call this method from within a function in the parent component. Can you guide me on how to achieve ...

Create an eye-catching hexagon shape in CSS/SCSS with rounded corners, a transparent backdrop, and a

I've been working on recreating a design using HTML, CSS/SCSS in Angular. The design can be viewed here: NFT Landing Page Design Here is a snippet of the code I have implemented so far (Typescript, SCSS, HTML): [Code here] [CSS styles here] [H ...

Trouble with React Context State Refreshing

Exploring My Situation: type Props = { children: React.ReactNode; }; interface Context { postIsDraft: boolean; setPostIsDraft: Dispatch<SetStateAction<boolean>>; } const initialContextValue: Context = { postIsDraft: false, setPostIs ...

Eliminate a specific choice from a drop-down menu in an Angular application

I am implementing a feature where clicking on a button adds more select drop downs. I want to ensure that the selected options in these new dropdowns do not duplicate any already chosen options. Below is the code snippet used for the select drop down: < ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...

Guide on utilizing a provider's variable in another provider within Ionic 2/3

In my code, I have a boolean variable called isConnection that is used to monitor network connection status. This variable is defined in a provider named 'network' and can be set to either true or false in different functions. Now, I need to acc ...

Executing TypeDoc on a Windows system results in zero files being created and no error messages reported

I have been working on generating documentation for a JavaScript application using TypeDoc. Unfortunately, I am facing an issue where TypeDoc is not outputting any files or errors. To get started, I installed TypeDoc within the project folder: npm instal ...

Angular 2+ Service for tracking application modifications and sending them to the server

Currently I am facing a challenge in my Angular 4 project regarding the implementation of the following functionality. The Process: Users interact with the application and it undergoes changes These modifications are stored locally using loca ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

When TypeScript tsc is unresponsive, there is no output or feedback provided

Just getting started with TypeScript! I've been working on transitioning my React.js project from JavaScript to TypeScript. I managed to resolve all the bugs and verified that it runs smoothly when using npm start. However, whenever I try to comp ...