Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams I get an error if I write this, the error is:

Type '{ backgroundColor: string; color: string; marginRight: number; borderRadius: number; borderRight: number; borderLeft: number; borderTop: number; borderBottom: string | false; }' is not assignable to type 'CSSProperties'.   Types of property 'borderBottom' are incompatible.     Type 'string | false' is not assignable to type 'string | number | (string & {}) | undefined'.       Type 'false' is not assignable to type 'string | number | (string & {}) | undefined'.

<span style={{backgroundColor:backgroundColor,color:color,marginRight:3,borderRadius:4,borderRight:0,borderLeft:0,borderTop:0,borderBottom: isCurrent && '3px solid #00416d'}}>{Symbol}</span> 
                You should use ternary operator like this borderBottom: isCurrent ? '3px solid &#00416d' : undefined
– Николай Гольцев
                Sep 26, 2020 at 11:25

Your error says Type 'string | false' is not assignable to type 'string | number | (string & {}) | undefined'.

This is because the expression: { ... borderBottom: isCurrent && '3px solid #00416d' gives string if isCurrent, otherwise gives false.

You should use something like isCurrent ? '3px solid #00416d' : 0 for borderBottom prop, which gives either string or number, both acceptable for CSSProperties.

Full example:

<span style={{
  backgroundColor: backgroundColor,
  color: color,
    marginRight: 3,
    borderRadius: 4,
    borderRight: 0,
    borderLeft: 0,
    borderTop: 0,
    borderBottom: isCurrent ? '3px solid #00416d' : 0
}}>{Symbol}</span> 

The problem is the type-checking, and you actually cannot assign a falsy value to the borderBottom property, which expects a string instead.

You can solve it easily, though:

<span style={{ 
  backgroundColor:backgroundColor, 
  color:color,
  marginRight:3,borderRadius:4,
  borderRight:0,
  borderLeft:0,
  borderTop:0,
  borderBottom: isCurrent ? '3px solid #00416d': 'initial'
  {Symbol}
</span> 

The problem of using a ternary operator is that you will need to define a fallback value, here is a simple trick to conditionally add a property to a JSON:

<span style={{ 
  backgroundColor:backgroundColor, 
  color:color,
  marginRight:3,borderRadius:4,
  borderRight:0,
  borderLeft:0,
  borderTop:0,
  ...(isCurrent && {borderBottom: '3px solid #00416d'})
  {Symbol}
</span>
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.