Alan2
Alan2

Reputation: 24602

How can I declare a variable to be an empty object before I add functions to it in Typescript?

I am trying to convert my javascript to Typescript and came up with another problem. Here's the code I have:

var util = {};

Then later in the code:

util.extendRegExp = function (regex, pre, post) {

    if (pre === null || pre === undefined) {
        pre = "";
    }
    if (post === null || post === undefined) {
        post = "";
    }

I tried to declare an interface like this:

interface Iutil = { extendRegExp (any) }

...
...
var util: Iutil = {};

but now I am getting an error message saying:

Can't convert {} to Iutil. util is missing the property extendRegExp 

Is there a way I can do the var util = {}

Upvotes: 2

Views: 1610

Answers (2)

Sly_cardinal
Sly_cardinal

Reputation: 13043

You can assert the empty object as your interface type when you assign it:

   var util: Iutil = {} as Iutil;

Then you can assign the function later.

If TypeScript still complains (e.g. no overlap between type or something like that) then you can do an assertion to any and then to your interface:

   var util: Iutil = {} as any as Iutil;

Upvotes: 8

basarat
basarat

Reputation: 276333

An alternative (I prefer) is to mark it as optional using ? because to be honest it is something that may or may not exist as soon as you start using type assertions:

interface Iutil { extendRegExp? (any) }
var util: Iutil = {}; // No error

Upvotes: 3

Related Questions