Home > front end >  Typescript: Override global type of history
Typescript: Override global type of history

Time:11-06

My typescript package contains a global type file that defines the history object like this:

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'd like to tell the compiler that the state property has a key property.

I tried this:

declare global {
  interface TypedHistory extends History {
    state: { key: string };
  }
  var history: TypedHistory;
}

console.log(history.state.key);

But I'm getting this error: Subsequent variable declarations must have the same type. Variable 'history' must be of type 'History', but here has type 'TypedHistory'.

How would I accomplish this? Preferably by declaring it in the same file I'm using the history object.

I'm not concerned whether or not this type definition always holds true, just how to accomplish this.

CodePudding user response:

Just had to move the var declaration outside the brackets. oops...

declare global {
  interface TypedHistory extends History {
    state: { key: string };
  }
}

declare var history: TypedHistory;

CodePudding user response:

If you need to overwrite the type of history in one place only, you can cast to a new type.

const myHistory = (history as unknown) as TypedHistory
console.log(myHistory.state.key) // works
console.log(myHistory.state.otherKey) // will show TypeScript error

However, due to the type of state currently being any, you should already be able to access history.state.key without any TypeScript errors. The only thing you would be missing in this case is that you would not get errors when trying to access other properties that might not exist.

  • Related