Gipsy King
Gipsy King

Reputation: 1577

Use function constructor + prototype as type, to avoid rewriting large part of codebase

Is there a way to get tsc to interpret an external module that exports a constructor function + prototype as a type?

While converting a large codebase to TypeScript, I found that typescript does not recognize external modules that export a function constructor and it's prototype as types.

function P() {...}
P.prototype.method = function() {...};
...
export = P;

If I later import this file, the type is simply the function signature and not a class-like type. This gives me type errors, e.g.:

import P = require('P');
var c:P = new P(); // cannot find name P
var c = new P(); // c has no type information

I know I should rewrite the code to use typescript's types with classes and interfaces, but it would be really nice if I could do that gradually and at least compile the project as it is with tsc. I recently found out that you can use the type of an external module that exports a singleton object like this:

var S = {...};
export S;

...and in another file:

import S = require('s');
interface C {
  s:typeof S; // notice the "typeof"
}

That you can use the type of an instance for typescript with typeof was not obvious and quite buried in the docs. I wonder if there is a trick like this when using normal javascript prototypes.

Upvotes: 0

Views: 434

Answers (2)

basarat
basarat

Reputation: 275957

As mentioned by Martijn you might want to just create a .d.ts. I suspect you have already arrived at that conclusion and looking for guidance on how to do that.

For your particular case p.d.ts:

declare module "P" {
    class P {
        method:Function;
    }
    export = P;
}

Usage:

/// <reference path="./p.d.ts"/>
import P = require("P");
var p = new P();
p.method(); // OKay

Upvotes: 1

Martijn
Martijn

Reputation: 1459

If i understand it correct, you have 'javascript' style typescript files.

You probably need to choose what you want to do with your current code. Leave it as .js or convert it to .ts

We had the same situation, we choose to keep the .js as it is and make .d.ts files for the .js files. Only for the functions and and classes we used from .ts and only when we needed.

At the end it gaves a very nice overview about the .js functions we used and what code was obsolete.

Upvotes: 2

Related Questions