Which TypeScript type must be used to define a class as a prop in the script setup of Vue 3?

Currently, I am working on a Vue 3 single file component that utilizes the script setup method. The challenge I am facing involves defining a prop that should accept values similar to those passed to the HTML class attribute. This means the prop could be a string, an expression, an array, or an object. However, when attempting to use withDefaults() to set a default value of an empty string to this prop, issues arise.

withDefaults(
  defineProps<{
    itemClass?: unknown
  }>(),
  {
    itemClass: '',
  }
)

This is then bound as

<div :class="itemClass">...</div>

I am striving to avoid using the type any, and have experimented with unknown without success in assigning it a default value. It appears that removing the default value altogether is a temporary workaround, although there may be scenarios where having a default value is essential.

Does anyone know if there exists a specific type tailored for the Vue class attribute?

Answer №1

The class binding value can come in different types:

  • string

    For example:

    <div :class="myStringProp">
    
  • Record<string, boolean> (Object syntax)

    For example:

    <div :class="{ active: true, error: true }">
    

It can also be a mixed array of these types:

  • (string | Record<string, boolean>)[]
    (Array syntax)

    For example:

    <div :class="['item', { active: true, error: true }]">
    

Therefore, the type for itemClass should be a union of these types:

defineProps<{
  itemClass?: string | Record<string, boolean> | (string | Record<string, boolean>)[]
}>()

Check out the demo here

Answer №2

In my Vue 3.2.39 project, I am implementing the following code snippet:

  import { HTMLAttributes } from "vue";

  const properties = defineProps<{
    style?: HTMLAttributes["style"];
  }>();

However, it still remains as any. Hopefully, Vue will introduce proper typing support in the near future.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing HTTP GET and POST requests in Angular 2 allows for the functionality of displaying, adding, and deleting objects within a list

Hey there, I'm completely new to dealing with HTTP and fetching data from the server. I've been scouring through various tutorials, examples, and questions on different platforms, but unfortunately, I haven't been able to find exactly what I ...

Navigating through pop-ups in Chrome: A guide to using Protractor

Currently, I am utilizing Protractor and am faced with the challenge of handling a pop-up from Chrome. My goal is to successfully click on the button labeled "Open magnet URI". For a visual representation of the issue, refer to the following image: picture ...

What is the process for building a reusable component from a static component in Vue 3?

I am delving into Vue 3 and Headless UI, and I have successfully created a ListBox component in App.vue to display a list of People which is functioning as expected. Now, I am aiming to transform it into a reusable component capable of displaying lists of ...

Required Ionic form field alert

Currently, I am developing a new app using ionic 3 and I am facing an issue with making inputs mandatory in my ionic-alert controller. Despite going through the ionic-component documentation and api documentation, I couldn't find a solution on how to ...

Retrieve user roles from core in Angular prior to implementing a guard

Hey, I'm facing an issue with my app.module setup. I have implemented lazy loading to load the core module and store roles in the core component. Everything works fine when I navigate from one page to another with the role guard applied. However, when ...

Creating a global component in Angular 2: A step-by-step guide

I attempted to create a component with global scope, but encountered an error: Uncaught Error: Can't export directive LanguageComponent from SharedModule as it was neither declared nor imported! To address this, I included the component in ShareModu ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

What is the best way to set up my page to detect the "enter" key input when the form is not created with the <form> tag?

Within the HTML code, data is received and stored in variables within my TypeScript file. At the end of the HTML, there is a button that was created separately from any user input containers. This button triggers a function that processes the information i ...

How to use Vue to eliminate text from a title within an array

I am having trouble removing the text "this | " from the titles in an array. Can anyone suggest the most effective method to accomplish this? Any assistance would be highly appreciated :) Here is my JavaScript code: let Feed=require('rss-to-json&a ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...

The challenges of dealing with duplicate identifiers caused by nesting npm packages in TypeScript

I am facing an issue with my project structure where I have a node_modules folder at the root level and another one within a subfolder named functions. The directory layout looks like this, ├── functions │   ├── index.js │   ├── ...

Navigating through pages. Learning to jump between different sections by simply clicking on numbers

Can you guide me on how to link a button from a page numbered cycle so that it opens a specific page? I have figured out navigation using arrows, but switching between pages is tricky for me. The data is sourced from an API with a total of 98 posts availab ...

Issue: The configuration for the rule "no-empty-interface" in .eslintrc.js is not valid

Is it acceptable to include an empty interface like the one shown below in the eslintrc.js file? interface RoutesProps {} https://i.sstatic.net/HwroT.png https://i.sstatic.net/pUKhC.png ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

What does Firefox need in order to fully support Vue.js debugging in PhpStorm?

As per PhpStorm documentation: Debugging Vue.js applications is currently only supported in Google Chrome and other Chromium-based browsers. Despite attempts by individuals like Jonathan Bossenger to make it work with Firefox, the conclusion remains: ...

Error message: "Vue3 JSX files are throwing a ReferenceError because React is not defined."

Currently, I am working on integrating storybook with antdv. However, when importing a tsx file that contains jsx within the button.stories.js file, I encountered an error stating "ReferenceError: React is not defined". You can view the error here. It is i ...

Creating a specialized optional map with a typed object containing a field that is strongly defined

I'm struggling to write code for registering strongly typed data loaders. I'm specifically facing issues with TypeScript in setting the map correctly. In the scenario below, M represents the service map and k is a list of services with a field ty ...