Ash
Ash

Reputation: 347

Logical operators with possible undefined value in typescript

I am getting a error and I don't fully understand why. I understand that it could be undefined and therefore I need to check if it exists but if I setup the code as below then I get the errors. However if I replace {showDescription && with {isFeatureBlock && description && inline it works perfectly. Why does it not work if I assign it to a const? Note: I have simplified to focus on the main issue.

The Code

isFeatureBlock is a boolean, description is optional string

const showDescription = isFeatureBlock && description

{showDescription && (
   <BlockDescription>
     {description}
   </BlockDescription>
 )}

The Error

  1. 'Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'

Upvotes: 0

Views: 1694

Answers (1)

Oblosys
Oblosys

Reputation: 15106

This code has no problems, but I assume in your real code, you use description in some place where a proper string is expected, and that is where the error is signaled. The reason why it works when you add description && is that in that case its type gets narrowed in the right-hand side of &&.

For description && SOME_EXP, TypeScript narrows the type of description from string | undefined to string inside SOME_EXP, as it can statically determine that description will not be undefined there. This only works if you use the variable directly in the left-hand side of the && expression though, so assigning it to a constant and using that constant won't work.

Upvotes: 1

Related Questions