Typescript:如何在不使用ts-ignore的情况下修补`history.pushState`?

问题描述 投票:0回答:1

我正在尝试以history路由库的方式来实现wouter API补丁,但使用Typescript而不是Javascript。

wouter库使用如下代码:

wouter

我已改用打字稿:

["pushState", "replaceState"].map(type => {
  const original = history[type];

  history[type] = function() {
    const result = original.apply(this, arguments);
    const event = new Event(type);
    event.arguments = arguments;

    dispatchEvent(event);
    return result;
  };
});

这似乎可行,但我不理解type WindowHistoryFn = (data: any, title: string, url?: (string | null)) => void; function patchHistoryPushState(){ const original: WindowHistoryFn = window.history.pushState; window.history.pushState = function(data: any, title: string, url?: (string | null)): void{ const result = original.apply(this, [data, title, url]); const event = new Event("pushState"); // @ts-ignore event.arguments = arguments; dispatchEvent(event); return result; }; } 行。

event.arguments = arguments类型没有Event字段。我应该实例化arguments的其他类型吗?如何重写上面的Typescript函数以不使用Event

typescript browser-history html5-history
1个回答
0
投票

由于JavaScript是鸭子类型的,因此您可以添加所需的任何内容。但是在TypeScript世界中,您将需要创建从ts-ignore扩展的自己的接口,也可以使用Event。如果使用CustomEvent,则需要填充CustomEvent而不是detail

您可以参考arguments

© www.soinside.com 2019 - 2024. All rights reserved.