Class bindings in Vue can accept strings, arrays and objects, according to the docs at https://vuejs.org/guide/essentials/class-and-style.html.
When setting up a component to accept a class
prop (e.g. someInnerComponentClass
), what is the best type to use for that?
This works if I only pass a string, but I want it to accept arrays and objects as if I were setting it like :class="['some-class', { 'conditional-class': myFlag }]"
on a root element:
const props = defineProps<{ class?: string }>();
I could try building up my own type that accepts strings, arrays of strings, arrays of objects, etc. but I feel like there's already a type that captures this that I can import, no?
My IDE (WebStorm) sees the class prop as a regular attribute:
I haven't found any type in Vue's core that is usable but we can use the information of the documentation to make up our own type. It can either be:
string
Record<string, boolean>
(Object syntax)(string | Record<string, boolean>)[]
(Combined)So you could do something like:
type Class = string | Record<string, boolean> | (string | Record<string, boolean>)[];
const props = defineProps<{ class?: Class }>();