Uncovering Module - which interface is missing a defined structure?

Can anyone explain why I am receiving this error in TypeScript 3.9.2:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.

The code triggering the error is shown below:

const Module = function(){

  function sayHello(){
    console.log('Hello');
  }

  return {
    sayHello: sayHello
  }
};

let module: any = new Module();

Answer №1

I highly suggest transitioning to ES6 classes for better code organization and readability. However, if you prefer using functions, the following solution will suffice:

 interface Module {
  sayHello: () => void;
}

const Module = function(){

  function sayHello(){
    console.log('Hello');
  }

  return {
    sayHello: sayHello
  }
} as any as { new (): Module; };
  
let module = new Module();

If you opt for using classes instead, you can simply implement it like this:

class Module {

  sayHello() {
    return console.log('Hello');
  }

};

let module = new Module();

module.sayHello();

Try it out in the playground.

Answer №2

new is typically used for creating instances of classes. However, the revealing module pattern involves a function that simply returns an object.

When implementing your module using this pattern, you should invoke it like a regular function rather than treating it as a class constructor.

let myModule = Module();
myModule.sayHello() // outputs 'Hello'

Check it out on 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

Passing data through Angular2 router: a comprehensive guide

I am currently developing a web application with the latest version of Angular (Angular v2.0.0). In my app, I have a sub-navigation and I want to pass data to a sub-page that loads its own component through the router-outlet. According to Angular 2 docume ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Utilize the nests cli swagger plugin to enable compatibility with external models

Exploring the functionality of the swagger plugin provided by nestjs, I am eager to try it out. While it works smoothly when defining a class like CreateUserDto, my goal is to incorporate types from a third-party library - specifically @adyen/api-library. ...

Why is it that in reactive forms of Angular, the parameter being passed in formControlName is passed as a string?

I am currently working on a reactive form in Angular. In order to synchronize the FormControl object from the TypeScript file with the form control in the HTML file, you need to utilize the formControlName directive. This is accomplished as shown below: f ...

A guide to creating a forward reference in React

I have a complex component that I need to type accurately. Here is what I am trying to achieve: interface Selector<V,T> { onChange(value:V): T } export const Selector = forwardRef<V, T>( ( { onChange }: Selector< ...

Create a function that is identical to the original, but omits the final

I am currently working on defining a type B that functions similarly to type A, but without the last parameter. I have attempted the solution below, however, it is still requiring 2 parameters instead of just one. type Callback = (msg: string) => void; ...

Handling mouse events with Angular 2 (tracking movement based on current position)

One of the features I want to implement for my user is the ability to move or rotate an object in a canvas using the mouse. The process involves calculating the delta (direction and length) between successive mouse events in order to update the position of ...

Determine the reference type being passed from a third-party component to a consumer-side component

I recently came across this issue with generics when using forwardRef in React: Property 'ref' does not exist on type 'IntrinsicAttributes' Let me explain my situation: import React from "react"; interface ThirdPartyComponen ...

Leveraging $sceDelegateProvider for allowing Youtube in Typescript

I'm currently facing an issue with my app where I am trying to enable users to input Youtube URLs for videos to be displayed on the site. However, before implementing this feature, I need to whitelist Youtube. How can I adjust my typescript file (app. ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Create a circle surrounding the latitude and longitude on a Bing Maps angular display

I successfully integrated the Bing map with Angular using the angular-map package, and now I want to draw a circle around a given latitude and longitude. To achieve this, I installed the following npm packages: npm install --save angular-maps npm ins ...

How can you implement Higher Order Components as a decorator in TypeScript?

Currently, I am attempting to develop a decorator that accepts an argument from React's Context provider. When creating a higher-order component (HOC), the process is straightforward: interface DashboardProps { user: User; } class Dashboard exten ...

Can Material UI be defined as a peerDependency while maintaining its types as a DevDependency?

Is there a way to set Material UI as a peerDependency while keeping its types as DevDependency? I'm currently working on a component library using React + Typescript, with components based on Material UI and Rollup as the module bundler. For example ...

Issue with Angular ngFor within a particular dialog window?

(respPIN and internalNotes are both of type InternalNotes[]) When the code in encounter.component.ts is set like this: this.ps.GetInternalNotes(resp.PersonID.toString()).subscribe(respPIN => { this.internalNotes = respPIN; }); An ERROR occurs: Err ...

When using React and Material UI, there seems to be an issue with the Popover component where calling `setAnchorEl(null)` on the onClose event does not properly

I am encountering an issue with a Popover (imported from MaterialUI) nested inside a MenuItem (also imported from MaterialUI). The open prop for the popover is set to the boolean value of anchorEl. The onClose function is supposed to handle setting anchorE ...

`mat chip component in Angular Material is malfunctioning`

Whenever I input a string, it does not display properly within the designated textbox. HTML <mat-form-field class="favorite-fruits"> <mat-label>Favorite Fruits</mat-label> <mat-chip-list #chipList aria- ...

Ways to verify the presence of isBrowser in Angular 4

Previously, isBrowser from Angular Universal could be used to determine if your page was being rendered in a browser (allowing for usage of features like localStorage) or if it was being pre-rendered on the server side. However, it appears that angular2-u ...

How can you partially update an entity in TypeORM using a query runner?

Updating a user's name partially is simple with the repository save method: await this.repository.save({ id: 1, name: 'john' }); However, when attempting to do the same using queryrunner, all fields must exist which throws an error stating ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

The error code TS2554 is triggered when the function expects between 1 to 2 arguments, but receives

When attempting to include { useHash: true } in RouterModule.forRoot, I encountered the following error. How can I add additional arguments? @NgModule({ imports: [RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- for debugging ...