Type not asignable (TypeScript 4.1.2)

别等时光非礼了梦想. 提交于 2021-02-08 08:54:26

问题


I'm using this piece of code from an old project (typescript 2) but it's not working with typescript 4.1.2. I'm trying to handle click events on desktop notification from an electron app (renderer process):

const nativeNotification = window.Notification;
const ProxyNotification = (title: any, options: any) => {
  const mirrorNotification = new nativeNotification(title, options);
  mirrorNotification.onclick = () => {
     // Handle click event.
  };
};
ProxyNotification.permission = nativeNotification.permission;
ProxyNotification.requestPermission = nativeNotification.requestPermission;
window.Notification = ProxyNotification;

The last line throws this error:

Type '{ (title: string, options?: NotificationOptions): void; permission: NotificationPermission; maxActions: number; prototype: Notification; requestPermission: (deprecatedCallback?: NotificationPermissionCallback) => Promise<...>; }' is not assignable to type '{ new (title: string, options?: NotificationOptions): Notification; prototype: Notification; readonly maxActions: number; readonly permission: NotificationPermission; requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise<...>; }'. Type '{ (title: string, options?: NotificationOptions): void; permission: NotificationPermission; maxActions: number; prototype: Notification; requestPermission: (deprecatedCallback?: NotificationPermissionCallback) => Promise<...>; }' provides no match for the signature 'new (title: string, options?: NotificationOptions): Notification'.

I would appreciate some help to fix it.

Kind regards.


回答1:


I assume, you want to extend Native window.Notification. Here is how I would do this:


const nativeNotification = window.Notification;

class ProxyNotification extends Notification {
        constructor(title: string, options?: NotificationOptions | undefined) {
                super(title, options)
        }
        customMethod() {
                console.log('hello')
        }
        /**
         * Here you can define your own methods and properties
         */
}

window.Notification = ProxyNotification


来源:https://stackoverflow.com/questions/65359425/type-not-asignable-typescript-4-1-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!