首页 > 解决方案 > TypeScript 中 react-router-dom 的匹配类型

问题描述

我有一个函数来检查是否currentUrl匹配特定的字符串:

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

    return match
  }

我不确定如何指定 return 的类型match

目前我收到错误:

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

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

在此处输入图像描述

标签: reactjstypescript

解决方案


Typescript is getting confused because the same name match refers to both the local match variable in your function and the match<T> interface imported from "react-router-dom". Usually interfaces and types use PascalCase and I'm not sure why this package doesn't.

If you are using the match<T> as your return type, then you need to include it in your import.

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

Normally if you forgot to include an import, you would get the error Cannot find name 'match'. But typescript did find the name match -- it found it as the name of your local variable, and that's why the error you get is telling you that you cannot use that variable as your return type.

Just import the interface and all is good. If you're as annoyed by the lowercase name as I am, you can also rename it when importing.

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

推荐阅读