TypeScript error with `!data?._type === 'page'` condition in Next.js slug file

6 replies
Last updated: Jul 31, 2022
I am changing the sanity-template-nextjs-landing-pages over to TypeScript.
One of the issues that I cannot resolve in my
[[…slug]].tsx
file is this:
When checking for non-page types with
if(!data?._type === 'page')
, I get a TS error
This condition will always return 'false' since the types 'boolean' and 'string' have no overlap.
The value of
_type
is always a string and I’m pretty sure
!foo === 'bar'
is the right syntax?
What’s the issue and how do I resolve it?
AI Update

This is actually a JavaScript/TypeScript operator precedence issue, not a Sanity-specific problem. The error message is telling you exactly what's wrong!

The issue is with your operator precedence. When you write:

if(!data?._type === 'page')

JavaScript evaluates this as:

if((!data?._type) === 'page')

So it's first negating data?._type with the ! operator (which gives you a boolean), and then comparing that boolean to the string 'page'. That's why TypeScript is complaining about comparing a boolean to a string.

The fix: You need to negate the entire comparison, not just the left side. Use parentheses:

if(!(data?._type === 'page'))

Or more idiomatically, use the inequality operator:

if(data?._type !== 'page')

The second option is cleaner and more commonly used in TypeScript/JavaScript code.

For your Next.js landing pages template, you'll also want to make sure you're properly typing your data object. If you're using Sanity's TypeGen (which generates TypeScript types from your schema), you can import the generated types and use them to get better type safety throughout your component. This will help catch these kinds of issues earlier and give you better autocomplete in your editor.

Show original thread
6 replies
Hi
user M
, wonderful that you’re doing that 🙂 I hope you will share the final code with us all!
I will have a look at the issue and get back at you
Until Sanity v3 is closer to an RC (with better TypeScript support), I’m just focusing on the NextJS part of that project.
So you don’t need feedback on this now?
Because I got some TS answers for you :cool_doge:

if (data?._type !== 'page')
:chefs-kiss:
It was a bug in the original code and in ts it would always return
false
because
!data
casts the string to a
boolean
, and
bool === string
will never be true. Removing the
!
will make it so it compares
string
with
string.
Such a simple solution. I never thought of
!==
. That is a simple option and something I could have attempted but never thought of! Thanks so much
user J
!
Our amazing team thought of it... 🙌 And pleasure 🙃

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?