At the end of the Showing Issue Details lesson (in the Viewing Issues section of Next.js part 2) Mosh mentions adding this line of code to render a 404 page if the URI path contains a non-numeric
id string (e.g.
if (typeof params.id !== "number") notFound();
Perhaps I’m missing something (totally plausible). If so, please help me understand because I can’t see how this would work. In all cases where
params.id is a string primitive,
typeof params.id results in
"string", so the suggested expression should always return
true and render a 404 page for every issue, even valid numeric IDs. I also tested it and could not get it to work the way the lesson implies.
This wasn’t a surprising result since the
typeof of a string primitive always results in
"string", even for numeric strings. And since we’re using a triple-not-equals there’s no type coercion happening (though, even double-equals operators don’t coerce numeric strings to numbers).
My solution is to parse the string and then test if the result is
if (Number.isNaN(parseInt(id))) notFound();
If you’re wondering why I checked for
NaN rather than using:
typeof parseInt(id) !== "number" // won't work!
typeof NaN results in
"number". That’s right:
NaN (which stands for Not A Number!) is…a number.
By the way, if you haven’t seen the classic short talk “WAT” by Gary Bernhardt (about 4 mins), check it out. It’s hilarious and may inspire you to read parts of the ECMAScript spec related to equality and type coercion.
Hope this helps.