4

I'm trying to figure out how to use type-safety provided by TypeScript with old plain constructor functions in JS. I have a very simple example, that looks straightforward, but I miss something and can't make it compile with TypeScript:

interface IMyService {
    new(): IMyService //I'm not sure if this line should be here, I just trying to make it working...
    doSomething(name: string): void
}

function MyService(this: IMyService): void {
    let _name = ""
    this.doSomething = (name) => {
        _name = name
    }
}

//The line below won't compile and it saying:
//"new" expression, whose target lacks a construct signature, implicitly has an "any" type
let service = new MyService();
service.setName("Test Name")  

What I'm missing? I know the preferred way of using TypeScript is with "class", but in my case I would like to use simple constructor functions.

1

2 Answers 2

1

You cant really type a function declaration (or at least i dont know how). However you can type a variable, and assign a function to it. And then we can define a constructor type:

interface IMyService {    
  doSomething(name: string): void;
}

interface IMyServiceConstructor {
  new(): IMyService;
}

const MyService: IMyServiceConstructor = function(this: IMyService){
  //...
};

That can be shortified through using an inline type:

const MyService: { new(): IMyService } = function(){
  //...
};
Sign up to request clarification or add additional context in comments.

1 Comment

I tried it in playground, but compiler still not likes it :(
0

What's stopping you from doing this:

class MyService {
  // declare instance method
  doSomething: (x: string) => void;

  // this is really your function
  constructor() {
    let _name = "";
    this.doSomething = (name) => {
      _name = name;
    }  
  }
}
let service = new MyService();
service.doSomething("Test Name"); 

This emits almost the same code as your original. It's still using a variable local to the constructor function scope, and an instance method instead of a class method. (Instance methods are generally frowned upon because you're creating closures for each instance but that's up to you.)

And TypeScript understands that MyService is newable and all the other goodness you want. Jumping through hoops with constructor type signatures and convincing TypeScript that your function is the right type doesn't seem worth it to me.

Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.