TanStackT
TanStackโ€ข2y agoโ€ข
15 replies
moderate-tomato

Type safe HistoryState in navigate

We're relying on HistoryState in our application and while params and search are both very well handled in the docs and the API,
I find HistoryState far less easy to work with.. probably a skill issue ๐Ÿ™‚ .

I keep running in to the TS error using navigate
navigate({ to: "/foo", state: { bar }});

Object literal may only specify known properties, and 'bar' does not exist in type 'NonNullableUpdater<HistoryState>'

The best workaround I found is when I want to use navigate is the following:
interface FooState extends HistoryState { 
  foo: string,
}
const newState = { foo: string } as FooState;
navigate({ to: "/foo", state: newState });

But this feels terrible and provides no type safety as I'm just casting it, would be nice to have something similar to validateSearch for State..
similarly when consuming state I have to do the same.
const Component = () => {
  const { location } = useRouterState();
  return location.state as FooState;
  return (
    <pre>{state.foo}</pre>
  );
}

Any suggestions how to work with state in a type safe matter using the lib is greatly appreciated.
Was this page helpful?