Xen_mar
Xen_mar

Reputation: 9702

Define constructor function (prototype pattern) in TS? This has type any

I've stumbled over something seemingly simple that I don't know how to fix. I want to use a simple constructor function (not a class):

const Person = function() {
    this.name = 'John'
}

The TS compiler says:

'this' implicitly has type 'any' because it does not have a type annotation.

But I'm not sure how I can set the type for this explicitly in this case?

Upvotes: 5

Views: 402

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37958

You can specify function's this type by using fake this parameter as explained here. But this is not enough as you also want this function to be newable. Type assertion can help here:

interface Person {
  name: string
}

interface PersonConstructor {
  new(): Person;
};

const Person = function(this: Person) {
    this.name = 'John'
} as any as PersonConstructor;

const p = new Person();

The above is allowed due to declaration merging, so Person is both type/shape and also value/constructor.

Playground

Upvotes: 2

Related Questions