What data type should I specify for a function that outputs an instance of a class?

When I create a function that returns a class, the structure looks like this:

function createClass() {
  return class implements ISomeInterface {/* ... */}
}

export { createClass }

However, I am now encountering a warning from ESLint:

Missing return type on function.

ESLint is referring to this ESLint rule.

What should I do to define the return type of createClass in order to satisfy ESLint?

Answer №1

Provided is the interface that corresponds to the instance type of an anonymous class:

interface ISomeInterface {
  prop: string;
  method(): void;
}

In addition, it can be beneficial to define an interface corresponding to the constructor of the class. This interface would encompass any static properties of the constructor, along with the construct signature of the class, as demonstrated below:

interface SomeInterfaceConstructor {
  new(prop: string): ISomeInterface;
}

The construct signature

new(prop: string): ISomeInterface
indicates that if you have a value c of type SomeInterfaceConstructor, you can invoke new c("foobar"); to obtain an ISomeInterface instance. It's important to note that this syntax does not imply that SomeInterfaceConstructor has a method named "new", despite the appearance.

By assigning a name to the constructor's interface, you can simply have createClass() return that specified type:

function createClass(): SomeInterfaceConstructor {
  return class implements ISomeInterface {
    constructor(public prop: string) { }
    method() {
      console.log("My prop is " + this.prop);
    }
  }
}

Testing the functionality, you can observe that it functions as expected:

const c = createClass();
// const c: SomeInterfaceConstructor;
const i = new c("foobar");
// const i: ISomeInterface
i.method(); // My prop is foobar
export { createClass }

When exporting createClass(), it might be worthwhile to also export the SomeInterfaceConstructor type, as well as ISomeInterface if it's not already exported or defined elsewhere.


Link to Playground for code

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

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

The local ESlint plugin is causing issues with installing dependencies on our CI environment

I have developed a personalized ESLint plugin specifically for one project and have not made it public. It is saved in a folder within my project because I only intend to use it internally, and I see no need to create a separate repository for it. However, ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

The functionality of connect-flash in Express JS is compromised when used in conjunction with express-mysql-session

I am facing a unique issue in my project. I have identified the source of the problem but I am struggling to find a solution. My project utilizes various modules such as cookie-parser, express-mysql-session, express-session, connect-flash, passport and m ...

Utilizing checkboxes for toggling the visibility of buttons in Angular

I want to dynamically show or hide buttons based on a checkbox. Here is the HTML code I am using: <input class="form-check-input" [(ngModel)]="switchCase" type="checkbox" id="flexSwitchCheckChecked" (change)=" ...

The type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app. Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty fo ...

The implementation of conditional parameter types in TypeScript

I am struggling with a function where the type of the first argument is determined by the second argument's value of true or false According to my logic, if userExists is true, data should be a string and if it's false, data should be a number. ...

Verify the type without making any assumptions about the checked type

Take a look at this type definition: interface ISmth<T> { id: number; data: T; } Now, I am interested in creating an array that contains elements of this type: var a = [{ id: 1, data: [], }, { id: 2, data: 4, }, { id: 3, data: "abc ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Converting a C# Dictionary<string,string> to a TypeScript Map<string,string>

Struggling to find the best approach for handling key:value pairs in TypeScript when receiving a dictionary object from the C# backend. Everything attempted so far has not yielded the expected results. This is the C# code snippet: var displayFields = ...

Is there a way to solely expand the type declarations from a separate class?

Imagine we have two distinct classes X and Y with 77 property-type declarations in common, but their methods, including constructors, are different: class X { public prop1: number; public prop2: string; //... public prop77: "hello"; constructor(){ th ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

Detecting typescript syntax errors: checking for if statements and calling class methods

When I'm debugging, I've noticed that the silly mistakes I make are often the hardest to spot. For example: if (id = userId) {..} And in class methods: let result = myClass.doThis; Oddly enough, VSCode doesn't catch these errors during co ...

What is the best way to notify the parent Observable of an inner Observable’s error or success within nested Observables?

How can the outer Observable be notified of success or error in nested Observables? Why are onNext and onCompleted undefined within the inner Observable? public updateDocument(item: Document): Observable<any> { this.firstUseOfflineContainer(); ...

Typescript causing issues with Material-UI theme.mixins.toolbar functionality

Currently, I am utilizing Material-UI to develop a React and Typescript website. The experience has been positive overall, but I am facing a specific issue. I have been trying to implement one of the code examples from their documentation, but unfortunatel ...

The HTTP DELETE request encountered a TypeError, stating that error.json is not a valid function

Within my Angular application, there is a feature that involves a "delete button". When this button is clicked, a confirmation popup appears asking the user if they are certain they want to proceed with the deletion. If the user confirms by clicking ' ...

Definition for the type react-navigation-v6 <Stack.Group>

I'm having trouble figuring out the proper type definition for a Stack group that includes screens (refer to TestStack.Group and the nested TestStack.Screen). The navigation stack: const TestStack = createNativeStackNavigator<TestStackParamList> ...