Skip to content

Instantly share code, notes, and snippets.

@drwpow
Last active December 10, 2022 03:19
Show Gist options
  • Save drwpow/4aa066b4fc7b8b4e89cdcc5373543a00 to your computer and use it in GitHub Desktop.
Save drwpow/4aa066b4fc7b8b4e89cdcc5373543a00 to your computer and use it in GitHub Desktop.
CSS Custom Properties in React with TypeScript

CSS Custom Properties in React with TypeScript

Ever encounter the following error when trying to do the following?

<div style={{ '--height': '32px' }}>
              ~~~~~~~~~~~~~~~~~~
// Type '{ "--height": string; }' is not assignable to type 'Properties<string | number, string & {}>'.
//   Object literal may only specify known properties, and '"--height"' does not exist in type 'Properties<string | number, string & {}>'.

To fix this, create a react.d.ts file in your project (the name doesn’t matter; just make sure it’s in TSConfig’s includes).

declare module "react" {
  // allow CSS custom properties
  interface CSSProperties {
    [varName: `--${string}`]: string | number | undefined;
  }
}

export {}; // if this file doesn’t `export` anything else, be sure to add this so it gets picked up

The best part about [varName: `--${string}`] is that it only allows CSS custom properties to your style object. Some solutions offer [index: string] which will ⚠️ disable typechecking entirely for the style object. Obviously not ideal!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment