我的 typescript 包包含一个全局类型文件,它定义了 history
对象,如下所示:
lib.dom.d.ts
interface History {
readonly length: number;
scrollRestoration: ScrollRestoration;
readonly state: any;
back(): void;
forward(): void;
go(delta?: number): void;
pushState(data: any, unused: string, url?: string | URL | null): void;
replaceState(data: any, unused: string, url?: string | URL | null): void;
}
declare var history: History;
我想告诉编译器 state
属性有一个 key
属性。
我尝试过这个:
declare global {
interface TypedHistory extends History {
state: { key: string };
}
var history: TypedHistory;
}
console.log(history.state.key);
但我收到此错误:
后续变量声明必须具有相同的类型。变量“history”必须是“History”类型,但这里的类型是“TypedHistory”。
我该如何实现这个目标?最好在我使用 history
对象的同一个文件中声明它。
我不关心这个类型定义是否始终成立,只关心如何实现这一点。
最佳答案
只需将 var 声明移到括号之外即可。哎呀...
declare global {
interface TypedHistory extends History {
state: { key: string };
}
}
declare var history: TypedHistory;
关于Typescript:覆盖历史记录的全局类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74331754/