Typing Dynamic Class Binding Attribute in VueJS
02 Mar 2024

When creating our own custom component, there are times where I find myself exposing a prop for the parent component to provide a HTML class attribute. For VueJS, we can have a variety of ways to set the CSS dynamically.

Example usage

We can define our dynamic class in this way and Vue will flatten it out in a single concentated string.

<MyCustomComponent
  :css="[
    'bg-green-200 shadow-lg',
    ['some-class', 'another-class'],
    {
      'some-state': state,
      'some-other-state': otherState,
    },
  ]"
>
  ...
</MyCustomComponent>

The ClassBinding type

As you can see we can have a recursively nested definition to define the dynamic css classes, as well as a plain-old string if the parent doesn’t want it to be dynamic.

So the Type looks like this:

type DynamicClassBinding = Array<
  DynamicClassBinding | Record<string, boolean> | string
>;

type ClassBinding = string | DynamicClassBinding;

Conclusion

Its nice that TypeScript supports recursive definition and this makes it easy to type the flexible dynamic class binding attribute for VueJS components.