Notion app logo
Struggling to stay organized and effective? Learn to master your time and tasks with the Effectively Notion course!

Fix CSS variable keys in style attributes in React and Typescript

How to define CSS variables in style attributes in react and Typescript

2021-02-23

Josh Comeau has a wonderful article about using CSS variables in style attributes in React props that has changed the way I write CSS in React (link).

Unfortunately, when using TypeScript, this method leads to a build error.

The Error

TS2326: Types of property 'style' are incompatible.
Type '{ "--color": string; }' is not assignable to type 'CSSProperties'.
Object literal may only specify known properties, and '"--color"' does not exist in type 'CSSProperties'.

How to Fix it

There are two ways to fix the build error:

  • cast the style object to React.CSSProperties
  • create an interface that extends React.CSSProperties

Cast the style object to React.CSSProperties

The part to note here is that the style object is followed by as React.CSSProperties:

 <StyledComponent style={{ "--color": colorValue } as React.CSSProperties}>
 {/* details... */}
 </StyledComponent>

The downside of casting is that it will allow any key arbitrarily. If you want to be explicit about what keys are available, try the next method, Extending CSSProperties.

Create an interface that extends React.CSSProperties

Extending CSSProperties has the advantage of allowing you to say which keys are acceptable:

import React, { CSSProperties } from 'react';

export interface CSSPropertiesWithVars extends CSSProperties {
  '--color': string;
  // any other vars you may use
}
Photo of Chase Adams

Hey, I'm Chase. I help aspiring entrepreneurs and makers turn their ideas into digital products and apps.

Freebies

Vector Arrow Scribbles
banner image for figma vector arrows scribbles

A figma community project of vectorized hand-drawn arrows.

Go To Figma
Vector Line Scribbles
banner for figma vector line scribbles

A figma community project of vectorized hand-drawn lines.

Go To Figma
Vector Shape Scribbles
banner image of figma vector shapes scribbles

A figma community project of vectorized hand-drawn shapes.

Go To Figma

Subscribe to my Newsletter

Every other week I publish the Curiously Crafted newsletter.

In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.

Online

I'm on almost all social media as @curiouslychase.

The curious logo of Chase Adams: glasses and a bow tie.stay curious.