In my TypeScript package, I have a global type file that contains the definition for the history
object as shown below:
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;
I want to inform the compiler that the state
property within the History
interface should have a nested key
property.
My attempt was to do this:
declare global {
interface TypedHistory extends History {
state: { key: string };
}
var history: TypedHistory;
}
console.log(history.state.key);
However, I encountered the following error message:
Subsequent variable declarations must have the same type. Variable 'history' must be of type 'History', but here has type 'TypedHistory'.
What approach should I take to achieve this? Ideally, I would like to declare it within the same file where I am using the history
object.
It is not important whether or not this type definition remains true at all times, just how I can implement it.