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

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

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 = {}

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 = {}

Share Improve this question edited Dec 29, 2014 at 9:37 Chris Martin 30.8k12 gold badges80 silver badges141 bronze badges asked Dec 29, 2014 at 9:28 Alan2Alan2 24.7k86 gold badges276 silver badges480 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 plains (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;

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744735323a4590709.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信