Skip to content

What is the correct way to use useParams with TypeScript? #363

Answered by molefrog
NoahELE asked this question in Q&A
Discussion options

You must be logged in to vote
import { useParams } from 'wouter';

export default function Hello() {
  const params = useParams(); // eslint report `Unsafe assignment of an `any` value.`
  return (
    <div>
      <h1>Hello, {params.name}</Heading>
    </div>
  );
}

How to correctly type the params variable? I tried adding generic type variables but it didn't work.

useParams can’t automatically infer the type of parameters used, so it returns any by default. So you need to cast it manually, or provide a generic argument: useParams<{ id: string }>(). Does that work?

Also, the types were broken for TS4.1 as shown here #360

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@NoahELE
Comment options

@molefrog
Comment options

@NoahELE
Comment options

Answer selected by molefrog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants