#How to type router params in loader function ?

1 messages ยท Page 1 of 1 (latest)

vapid ice
#

I have a loader function export const loader = async ({ params }: LoaderArgs) => { const movie = await fetchMovieById(params.movieId) return json({ movie }) } and I want the params.movieId to have string type but I am not being able to figure out how. Can someone help me ?

balmy raft
#

it should be string | undefined, no?

vapid ice
#

Yes that's the type I am getting but why would it be undefined ? sorry if its a dumb question

balmy raft
#

Good question

#

I don't know for sure I'm guessing maybe there's some edge case where you have a route like /movies/$id but someone manages to visit the route without filling in the param

#

let me have a play

vapid ice
#

Alright thank you ๐Ÿ™‚

balmy raft
#

#react-router-general message

#

So it might be undefined because TypeScript doesn't know whether the param you're trying to get is actually valid

#

obviously you know that params.movieId is a string because you have a file called $movieId

#

but typescript can't tell that

#

so if you were to try and do, say, params.songId instead, it needs to return undefined there because that isn't a valid param for that route

#

you can probably quite safely cast it to a string if you wanted to

vapid ice
#

so casting is the way to go for now

#

thank you benslv, that's helpful ๐Ÿ™‚

woeful flicker