0
votes

Why this code in typescript 3.9.2 gets me this error:

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

Code is:

const Module = function(){

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

  return {
    sayHello: sayHello
  }
};

let module: any = new Module();
2

2 Answers

0
votes

I'd strongly recommend you to use ES6 classes. but in case you want to keep using functions, then the below solution will work for you:

 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 want to use classes then you can simply write:

class Module {

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

};

let module = new Module();

module.sayHello();

Playground.

0
votes

new is for instantiating classes. But the revealing module pattern is just a function that returns an object.

You want to create your module by calling it like any normal function, and not like it's a class constructor.

let module = Module();
module.sayHello() // logs 'Hello'

Playground