0

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'
2
  • Can you explain what is this rows: {showDescription && ( <BlockDescription> {description} </BlockDescription> )}? Is it object or something else? Commented Sep 19, 2017 at 11:32
  • It just returns a div with some text in it, though I noticed need to update errors as i included an error from something else. The object undefined is related to another issue. My mistake. The first error still applies. Commented Sep 19, 2017 at 11:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

BTW, thanks for the explanation that is exactly what I needed, I did not realise the type would get narrowed was really confused!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.