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?
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:
- www.example.com
router.query.blogId = undefined - www.example.com/?blogId=1&blogId=2
router.query.blogId = [1, 2] - 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.