Warm tip: This article is reproduced from stackoverflow.com, please click
typescript

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

发布于 2020-05-08 07:28:45

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...

Questioner
Justin808
Viewed
183
basarat 2020-02-23 08:12

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;