TS+Vue3: The Perfect Match for Data Type Assignment

When working with my components, I am interested in using

<script setup lang="ts">
. However, I encountered a type issue. Here is an example of a standard component using
<script lang="ts">
:

props: {
    modelValue: {
      type: [Boolean, String, Number, Array as () => Array<string | number>],
      required: true,
    },
    value: {
      type: [Boolean, String, Number, Array as () => Array<string>],
      default: "",
    },
    label: {
      type: [String, Number],
      default: "",
    },
}

Now, how can we correctly define these types within the interface for a component using

<script setup lang="ts">
?

interface Props {
  modelValue: [Boolean, String, Number, Array as () => Array<string | number>]
  value: [Boolean, String, Number, Array as () => Array<string>]
  label: [String, Number]
}
const props = defineProps<Props>()

Answer №1

To merge different types in TypeScript, utilize union types. For example, consider this constructor array:

[Boolean, String, Number, Array as () => Array<string | number>]

...transforms into this type declaration in TypeScript:

boolean | string | number | (string | number)[]

Hence, the corresponding TypeScript interface for your initial code would be:

interface Props {
  modelValue: boolean | string | number | (string | number)[]
  value: boolean | string | number | string[]
  label: string | number
}
const props = defineProps<Props>()

To assign default values to the props, use withDefaults():

const props = withDefaults(defineProps<Props>(), {
  value: '',
  label: '',
})

...or opt for object destructuring with default values:

const {
  modelValue = '',
  value = '',
  label = '',
} = defineProps<Props>()

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

Unable to generate paths in Ionic 3

I am trying to view the actual route on the URL, but I'm having trouble figuring out exactly what needs to be changed. I've been referring to the documentation at: https://ionicframework.com/docs/api/navigation/IonicPage/ However, I keep encoun ...

Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array. The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array. D ...

The state of vuex does not reveal its length

Within the vuex state, there is a variable 'images' defined as an array. When I use console.log(state.images), it shows output in this format: [__ob__: Observer] 0: {…} 1: {…} 2: {…} 3: {…} 4: {…} length: 5 __ob__: Observer {value: Arr ...

Vue JavaScript and Making AJAX Requests

I'm currently in the process of transitioning from jQuery to Vue.js, but I'm encountering some challenges when trying to execute an Ajax call using Vue Resource. Here is a sample script that includes both jQuery and Vuejs attempting to access the ...

Simultaneous Vue components

Here's an example of a string: "Greetings Earthlings! I come in peace." Along with a set of words. ["Greetings", "Earthlings", "peace"] I want to automate the process of enclosing matching words within Vue components. For instance, it should look ...

Guide to combining two elements in a Vue.js array

I seem to be stuck at this point... I have retrieved a list from my database which can have the same Id_Plane but different DateCreated, Starts, Ends... How can I merge two elements with the same ID into one element with 2 DateCreated, Starts, Ends? Tha ...

Using this.router.push for transition while also monitoring the completion of the animation in VUE CLI

I am seeking assistance as a beginner in creating web applications for the first time. I am using Vue Cli and have successfully implemented an animated Lottie element that triggers a page transition upon click. However, I am now facing the challenge of del ...

Vue: Error - Unable to execute _vm.myFunction as it is not a function

I'm currently working on adding a basic button to a .vue file that will log a message to the console. Here's the code I have so far: <template> <div> <button v-on:click="sayHello()">Click me</button> < ...

Ways to employ data binding for extracting a user-input value and performing multiplication operations with the enclosed {{ ...}} tags

My API response includes the price of a product, which is represented as {{price}} I have a system where I can add or reduce the number of products: <div class="number-input"> <h2>Price: {{price }}</h2> <button oncli ...

retrieve the name or path of the route currently being accessed

Here is the navigation bar code snippet: <nav class="menu"> <a routerLink="textArea" class="menu-item">text-area</a> <a routerLink="dropdown" class="menu-item">dropdown</a& ...

Looking for a JavaScript library to display 3D models

I am looking for a JavaScript library that can create 3D geometric shapes and display them within a div. Ideally, I would like the ability to export the shapes as jpg files or similar. Take a look at this example of a 3D cube: 3d cube ...

I found myself in a bit of a predicament as I tried to transition a petite

Recently, I've been working on a small project that is built using pure HTML, CSS, and JavaScript. As I am delving into the realm of Vue.js, I decided to challenge myself by migrating this project to Vue.js. Here is how it currently functions with Ja ...

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Is it possible to constrain generic indexed access parameters?

Consider the following scenario: type Group = | { type: "string"; payload: string; } | { type: "number"; payload: number; }; A function can be created as shown below: const groupFunction = <T exte ...

Develop a function that returns a specific type that has been mapped

I'm currently working on a method that loops through an object and replaces key-value pairs where the value matches { _id: Types.ObjectId } with a new key and maps the value to the string representation of _id. For example: { "name": " ...

Is there a way to incorporate the ACE code editor into a Vue project without relying on its built-in Vue

Just starting out with Vue and I'm looking to incorporate the ace code editor (this package) into my project. However, I want to avoid using the vue2-component & vue3-component versions for learning purposes. How can I achieve this? What's t ...

Creating a duplicate of the useFetch function within a custom hook: Here's how

I'm struggling to generate a reusable hook, but the behavior I'm getting is not what I anticipated /composables/fetch.ts export const useFetchWithErrorHandler = async (url: string, options?: FetchOptions) => { const route = useRoute(); co ...

Understanding the Access-Control-Allow-Headers in preflight response for Wordpress and VueJS

Attempting to retrieve a route from candriam-app.nanosite.tech to candriam.nanosite.tech has proven challenging. Despite various attempts to allow headers, I continue to encounter this CORS error: Access to fetch at 'https://xxxA/wp-json/nf-submission ...

the importance of attribute positioning in css classes

I am attempting to change the color of a paragraph element's content by utilizing a class binding on specified text: the code below illustrates my attempt, however it is not yielding the intended results <p :class="changeColor"> hello ...

Having trouble importing a tailwind CSS file into a Remix.js project without TypeScript throwing an error

https://i.sstatic.net/pvyUf.png I've attempted to implement the solution found here but unfortunately, it's still not working for me. Below are my configuration files: remix.config.ts: /** @type {import('@remix-run/dev').AppConfig} * ...