简体   繁体   中英

How do I define an typescript interface for a constructor that also is an object?

I get this error:

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.

This is my interface:

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

and this is the usage:

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

With the Twitch API window.Twitch.Embed is a constructor and an object...

I would define it as a single object instead of splitting it in a union.

Here is the complete example

// 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;

It looks to me like you're trying to use the Twitch interactive player in an Angular/Typescript project.

I've recently encountered the same problem and that's why I decided to implement a Typescript wrapper for the Twitch interactive embed player. This is 100% compatible with Angular so if you still need a way to achieve this please check this repository out. Hope it helps ^ ^

https://github.com/frozencure/twitch-player

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM