Magofoco
Magofoco

Reputation: 5466

Match type for react-router-dom in TypeScript

I have a function that checks if the currentUrl matches a specific string:

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

    return match
  }

I am not sure how to specify the type of the returnmatch.

Currently I am getting the error:

'match' refers to a value, but is being used as a type here.ts(2749)

However, If I hover on const match = matchPath(currentUrl... it tells me the type is match<{}> | null

enter image description here

Upvotes: 1

Views: 721

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42208

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"

Upvotes: 4

Related Questions