3

I have a property in my component that is supposed to get an array of valid CSS properties:

interface MyComponentProps {
    cssProperties: (keyof CSSStyleDeclaration)[];
}

const MyComponent = ({ cssProperties }: MyComponentProps) => {
    //
}

The problem is that CSSStyleDeclaration stores styles as an object with property names in camel case. I need real CSS property values, hyphened. So background-color instead of backgroundColor. I know there's also React.CSSProperties type, but it uses camel-cased properties too, while allowing for unitless numeric values.

Is there a TypeScript type to use original, hyphened CSS property names?

2 Answers 2

2

There is this library csstype which is used by MUI, emotion and some other popular component libraries.

Which allows you to use the hyphen props

import CSS from "csstype";

interface MyComponentProps {
  cssProperties: (keyof CSS.PropertiesHyphen)[];
}

const MyComponent = ({ cssProperties }: MyComponentProps) => {
  //
}

<MyComponent cssProperties={["color", "background-color"]} />;
Sign up to request clarification or add additional context in comments.

2 Comments

I'll have a look in a bit.
Okay, it works as expected, thanks. I was sure there must be a package for this!
1

Use Kebab type available here. Camelcased CSS properties will be transformed into kebabcase.

type Kebab<T extends string, A extends string = ""> =
    T extends `${infer F}${infer R}` ?
    Kebab<R, `${A}${F extends Lowercase<F> ? "" : "-"}${Lowercase<F>}`> :
    A

type Props = {
    cssProps: Kebab<keyof React.CSSProperties>[];
}

const Component = (props: Props) => null;

const App = () => (
  <Component cssProps={['min-width']} />
);

Typescript Playground

4 Comments

I thought about that, but I'd need to investigate whether CSSStyleDeclaration has some edge cases (pun!) where converting the case wouldn't convert to a CSS property. Also I'd like to make 100% sure there are no alternatives.
Also, it loses vendor prefixed properties, however I could live without them.
@RoboRobok According to the W3C standards all of the CSS properties are kebabcased. There should be not any problems with it, except vendor prefixes.
Thanks, I selected another answer as it uses less trickery :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.