最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Only void function can be called with the "new" keyword - Stack Overflow

programmeradmin2浏览0评论

I'm trying to use the Foundation's Reveal plugin in my Typescript code in following way (altered for readability):

var popup = new Foundation.Reveal($('#element'));

and I'm getting following error during compilation (in the end it does compile and work anyway):

TS2350: Only a void function can be called with the 'new' keyword.

How should I write it then?

Typescript Playground - code illustrating the problem

I'm trying to use the Foundation's Reveal plugin in my Typescript code in following way (altered for readability):

var popup = new Foundation.Reveal($('#element'));

and I'm getting following error during compilation (in the end it does compile and work anyway):

TS2350: Only a void function can be called with the 'new' keyword.

How should I write it then?

Typescript Playground - code illustrating the problem

Share Improve this question asked Jun 13, 2016 at 12:09 WiktorWiktor 3,0595 gold badges18 silver badges23 bronze badges 3
  • I think you are messing things up. Why would you want to do a new if Reveal is a function that returns an object? – iberbeu Commented Jun 13, 2016 at 12:14
  • It's the only way I made it work so far... – Wiktor Commented Jun 13, 2016 at 12:17
  • 2 Based on the code in playground you should do: var popup = Foundation.Reveal($('#element')) (that is, without the new) – Nitzan Tomer Commented Jun 13, 2016 at 13:52
Add a comment  | 

3 Answers 3

Reset to default 11

I find a way to shut the typescript compiler up, but this will give up the type check(Do it with your caution).

var popup = new (Foundation.Reveal as any)($('#element'));

More example:

function User2(name) {
    if (this instanceof User2) {
        this.name = name;
    }
    else {
        return new (User2 as any)(name);
    }
}

Based on the interface:

interface FoundationSitesStatic {
    Reveal(element:Object, options?:IRevealOptions): Reveal;
}

you cannot call it with the new operator (used to call a constructor).

So fix:

var popup = Foundation.Reveal($('#element'));

I think you want this:

interface FoundationSitesStatic {
    Reveal: new (element: Object, options?: IRevealOptions) => Reveal;
}

Which lets you do what works without TypeScript errors and without sacrificing type safety!

const popup = new Foundation.Reveal($('#element'));
发布评论

评论列表(0)

  1. 暂无评论