【问题标题】:Match type for react-router-dom in TypeScriptTypeScript 中 react-router-dom 的匹配类型
【发布时间】:2020-09-24 10:21:13
【问题描述】:

我有一个函数可以检查 currentUrl 是否与特定字符串匹配:

  const checkingPage= (currentUrl: string): match<{}> | null => {
    const match = matchPath(currentUrl, {
      path: '/options/:optionId',
      exact: true,
      strict: false
    })

    return match
  }

不知道如何指定returnmatch的类型。

目前我收到错误:

'match' 指的是一个值,但在这里被用作一个类型。ts(2749)

但是,如果我将鼠标悬停在 const match = matchPath(currentUrl... 上,它会告诉我类型是 match&lt;{}&gt; | null

【问题讨论】:

  • 我不确定如何在返回match 的函数中定义返回类型。如果我这样做 const checkingPage= (currentUrl: string): matchPath&lt;RouteParams&gt; 它仍然抱怨说 matchPath&lt;RouteParams&gt; refers to a value, but is being used as a type here

标签: reactjs typescript


【解决方案1】:

Typescript 变得混乱,因为同名 match 指的是函数中的本地 match 变量和从“react-router-dom”导入的 match&lt;T&gt; 接口。通常接口和类型使用 PascalCase,我不知道为什么这个包没有。

如果您使用match&lt;T&gt; 作为您的返回类型,那么您需要将它包含在您的导入中。

import {match, matchPath} from "react-router-dom"

通常,如果您忘记包含导入,您会收到错误 Cannot find name 'match'。但是打字稿确实找到了名称match——它发现它是你的局部变量的名称,这就是为什么你得到的错误告诉你不能使用那个变量作为你的返回类型。

只需导入界面,一切都很好。如果你和我一样对小写名称感到恼火,你也可以在导入时重命名。

import {matchPath, match as Match} from "react-router-dom"

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2017-09-25
    • 1970-01-01
    • 2017-12-05
    • 2017-10-22
    • 2019-10-22
    • 2021-05-10
    • 2020-09-03
    • 2021-03-30
    相关资源
    最近更新 更多