Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing dynamic url parameter to a function without implicit typing (next.js typescript)

Using useRouter to a function strictly receiving string type parameter produces following error:

Type ‘string | string[] | undefined’ is not assignable to type ‘string’.
Type ‘undefined’ is not assignable to type ‘string’

Is there a way how to fix the error without implicit typing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { useRouter } from 'next/router'
import { useBlogQuery } from '@graphql/generated'

const router = useRouter()
const blogId = router.query.blogId

const BlogQuery = useBlogQuery({
    variables: {
        id: blogId
    },
})

>Solution :

This is actually a useful type-checking error.

Consider:

  1. www.example.com router.query.blogId = undefined
  2. www.example.com/?blogId=1&blogId=2 router.query.blogId = [1, 2]
  3. www.example.com/?blogId=1 router.query.blogId = 1

You can do this if you are 100% sure cases 1 & 2 will never happen:

const blogId = router.query.blogId as string;

But probably better to add some logic around blogId being either undefined or an array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading