Created
October 13, 2025 21:15
-
-
Save jossmac/83c97d4a64ba8c84b99d36f7dc8af2bc to your computer and use it in GitHub Desktop.
CSS custom properties in TS/React `style` attribute. Alternative to module declarations, or comment directives.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { CSSProperties } from 'react'; | |
| type StyleVars = Record< | |
| `--${string}`, | |
| string | number | boolean | undefined | null | |
| >; | |
| /** | |
| * Type casting identity function. Maintains the autocompletion and type safety | |
| * of `CSSProperties`, while allowing the addition of CSS variables. | |
| * | |
| * @example | |
| * <div | |
| * className="flex items-[--align] transition-opacity" | |
| * style={styleVars({ | |
| * opacity: props.visible ? 1 : 0, | |
| * '--align': props.align, | |
| * })} | |
| * /> | |
| */ | |
| export function styleVars(properties: CSSProperties & StyleVars) { | |
| return properties as CSSProperties; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Module declarations can cause issues, especially when working in a large repo with lots of dependencies. A bit like modifying built-in prototypes, it'll eventually come back to bite you.
Naive type assertions undermine type safety.
Comment directives are probably the "safest" approach but they get tedious and can look messy.