xoux
xoux

Reputation: 3494

How to type constructor functions that are properties of an object in TypeScript?

I have an object with a property that is a constructor function. How do I type this correctly:

interface MyObj {
    constructor: () => ({ init: () => void })
}

const myObj = {
    constructor: function(this: any) {
        this.init = function() {
            this.var = 5;
        }
    }
}

This works without errors, but that's because I have the this: any in the constructor function. If I remove that I have the error

Property 'init' does not exist on type '{ constructor: () => void; }'

Property 'var' does not exist on type '{ constructor: () => void; }'

What is the correct way to type constructor functions like this?

Upvotes: 0

Views: 37

Answers (1)

Artem Bozhko
Artem Bozhko

Reputation: 1854

You should use the keyword "new" to describe the type of constructor function

See example below:

First we define the constructor options interface

interface MyObjConfig<T> {
    init: (instance: T) => void;
}

Next is the interface for MyObj

interface MyObj<T> {
    constructor: new (config: MyObjConfig<T>) => T;
}

Now we create concrete implementations of MyObj and some test class

class MyObjItem {
    public var: number;
}

const myObj: MyObj<MyObjItem> = {
    constructor: MyObjItem
};

And now we can use myObj to construct new instances

const initiator = (instance: MyObjItem) => {
    instance.var = 5;
};


const concreteInstance = new myObj.constructor({ init: initiator });

Upvotes: 1

Related Questions