温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How do I define an typescript interface for a constructor that also is an object?
typescript

其他 - 如何为也是对象的构造函数定义Typescript接口?

发布于 2020-05-12 06:47:11

我收到此错误:

This expression is not constructable.
  Not all constituents of type '(new (arg0: HTMLDivElement, arg1: object) => Embed) | { VIDEO_READY: string; }' are constructable.
    Type '{ VIDEO_READY: string; }' has no construct signatures.

这是我的界面:

declare global {
  interface Window {
    Twitch: {
      Embed: new (arg0: HTMLDivElement, arg1: object) => Embed;
    } | {
      Embed: {
        VIDEO_READY: string;
      };
    };
  }
}

这是用法:

    embed = new window.Twitch.Embed(video.value, {
      video: props.twitch,
    });
    embed.addEventListener(window.Twitch.Embed.VIDEO_READY, () => {
      player = embed.getPlayer();
      player.pause();
      resizeIframe();
    });

使用Twitch API时window.Twitch.Embed,构造函数和对象都是...

查看更多

提问者
Justin808
被浏览
5
basarat 2020-02-23 08:12

我将其定义为单个对象,而不是将其拆分为联合。

这是完整的例子

// Your usage
embed = new window.Twitch.Embed(htmlDiv, {
    video: 123,
});
embed.addEventListener(window.Twitch.Embed.VIDEO_READY, () => {
    // ... 
});


// The definition
declare global {
    interface Window {
        Twitch: {
            Embed: {
                new(arg0: HTMLDivElement, arg1: object): Window['Twitch']['Embed'];
                VIDEO_READY: string;
            }
        }
    }
}


// Some excess irrelevant stuff
declare var embed: any;
declare var htmlDiv: HTMLDivElement;
export const exportSomething = 123;