4

I'm using React and Styled Components and I have a function that accepts a string of a css attribute. I want to type it to validate that the string is a valid css attribute (color, background-color, etc...)

function doSomething(cssPropertyName: SomeType) {
}

doSomething('border-color'); // No error
doSomething('non-existing-css-property'); // Should give an error

How can I achieve this?
Thanks!

2
  • 2
    Ref: This maybe? github.com/frenic/csstype, with (prop: keyof CSSProperties) => ... Though you'd need to provide borderColor instead of border-color (for example). Commented Feb 15, 2021 at 8:28
  • Yes! That's the stuff. I'm good with the camel case. Do you want to add this as the answer? Thanks! Commented Feb 15, 2021 at 9:00

1 Answer 1

5

With: https://github.com/frenic/csstype I think you can simply use:

function doSomething(prop: keyof CSSProperties) {
}

doSomething('borderColor'); // No error
doSomething('non-existing-css-property'); // Should give an error
Sign up to request clarification or add additional context in comments.

Comments

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.