phreed phreed - 3 years ago 167
Javascript Question

How to define a Typescript constructor and factory function with the same name?

I am writing a Typescript definition file for an existing Javascript library.
In this library there are functions which can be called as constructors or factories.
How do I write the typings in a compatible fashion?

Here is a specific example of the calls that need to be supported according to the README:

var streamParser = N3.StreamParser();
var streamParser = new N3.StreamParser();

My current approach is to only support the factory.

function Parser(options?: ParserOptions): N3Parser;

The obvious approach to get the
to work is to create a class.

class Parser {
constructor(options ? : ParserOptions);

But these two approaches are incompatible.
The opening paragraph of the declartion-file deep-dive indicates this is possible but no example is given.

The following two definitions are compatible but... so, what?

interface Parser {
new: (options ? : ParserOptions) => N3Parser;

function Parser(options ? : ParserOptions): N3Parser;

Answer Source

You can follow the same thing that is done in the lib.d.ts with Array and ArrayConstructor:

interface Parser {}

interface ParserConstructor {
    new (options?: ParserOptions): Parser;
    (options?: ParserOptions): Parser;

declare const Parser: ParserConstructor;

let p1 = Parser();
let p2 = new Parser();

(code in playground)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download