Reputation: 3430
I am editing an app using TypeScript React and Meteor. Currently I got the following state:
{user && ( ... )}
This shows some data only if the visitor is a logged in user. I although want to show the data only if the tournament is not cancelled. So I tried to add
{user && !tournament.state === 'cancelled' && ( ... )}
which does not work. I receive the following linter message:
Operator '===' cannot be applied to types 'boolean' and '"cancelled"'.
How can I solve this puzzle?
Upvotes: 1
Views: 24493
Reputation: 1074295
!tournament.state
negates tournament.state
, not the ===
that follows, resulting in true
or false
for that part, giving you true === 'cancelled'
or false === 'cancelled'. Hence the issue with using
===` on a boolean and a string.
Use !==
:
{user && tournament.state !== 'cancelled' &&
Technically, you can use parentheses as well, but it wouldn't be idiomatic:
{user && !(tournament.state === 'cancelled') &&
Upvotes: 5
Reputation: 3958
TypeScript complains because you are trying to compare a boolean value: !tournament.state
to a string: 'cancelled'
.
The !
symbol is going to turn a truthy/falsy result into an boolean. This happens because assuming tournament.state
is equal to 'cancelled'
:
!tournament.state = !'cancelled' = false
The triple equals operator then checks both value and type. Your code will not only be disliked by TypeScript, it is also incorrect, as every value of tournament.state
is going to fail the check, because it will always end up as a boolean against a string. What you need is:
{user && tournament.state !== 'cancelled' && ( ... )}
Upvotes: 2