Omar Penny
Omar Penny

Reputation: 193

Type {} is not assignable to type CSSProperties error

How can I assign inline CSS to an element? 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> 

Upvotes: 19

Views: 45099

Answers (3)

Hector Manuel
Hector Manuel

Reputation: 484

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>

Upvotes: 2

Mario Vernari
Mario Vernari

Reputation: 7304

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> 

Upvotes: 4

Δ O
Δ O

Reputation: 3710

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> 

Upvotes: 12

Related Questions