Reputation: 24602
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
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
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