提问者:小点点

如何设置react-router-dom的类型?


在我的React typescript项目中,我有以下代码:

import { useLocation } from 'react-router-dom';

export function App() {
  const location = useLocation();
  const background = location.state && location.state.background;
  ...
}

Typescript抱怨“属性‘背景’在类型‘{}’上不存在。ts(2339)”我应该如何扩展位置类型并让ts满意?


共1个答案

匿名用户

由于react-router-dom useSite不接受通用props作为useSite

import { useLocation } from "react-router-dom";
import type { Location } from "react-router";

// T is to make a generic type so you can use it wherever you want. Feel free to export in into another common types file.
interface LocationWithState<T> extends Location {
  state: T;
}

interface LocationState {
  background: boolean;
  foo: number;
}

export function App() {
  const location = useLocation() as LocationWithState<LocationState>;
  const background = location.state.background; // works ✅
  const foo = location.state.foo; // works ✅
  const bar = location.state.bar; // error ❌
}