How to use JSDoc to provide property types to styled.div?

Viewed 328

When I use VS Code, I can add a jsconfig.json file to get type assistance via IntelliSense. I'm not interested in switching to TypeScript, so I'm using JSDoc to annotate types where needed.

I found that I can add props to a given component like this:

const StyledNode = styled(
  /** @type {React.ComponentType<React.ComponentProps<Box> & {level: number}>} */ (Box)
)`
  margin-left: ${p => p.level * 3}em;
`

This is zero-cost: I'm getting type assistance when using StyledNode as well as when using level in the CSS.

However, if I want to style a regular div, I have to do

const StyledNode = styled(
  /** @type {React.ComponentType<React.DomAttributes & {level: number}>} */
  (React.forwardRef((p, ref) => <div ref={ref} {...p} />))
)`
  margin-left: ${p => p.level * 3}em;
`

which doesn't seem like zero-cost to me. The problem is that I can't see a way to pass the type parameter to styled<type> via JSDoc.

What is the most optimal way to provide the parameter types to the css template functions in styled.div?

1 Answers

You can import import * as CSS from 'csstype' as global

and use jsdoc hack!

ex: @param {CSS.Property.FlexDirection} [props.flexDirection] - descriptions

enter image description here enter image description here

You can install the packages as Dev for avoid polluting, and using only inside jsdoc.

npm i csstype -D -S

is this help you ?

Related