我正在尝试以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
?
由于JavaScript是鸭子类型的,因此您可以添加所需的任何内容。但是在TypeScript世界中,您将需要创建从ts-ignore
扩展的自己的接口,也可以使用Event
。如果使用CustomEvent
,则需要填充CustomEvent
而不是detail
。
您可以参考arguments