How can you inline cast a prop in Vue 2 using Typescript?

I'm currently working on a Vue 2 NuxtJS project with Typescript and I want to make use of the unknown keyword in Typescript.

Within my component, I am receiving a prop declared as follows:

props: { 
  items: {
    type: Array as () => LabelValuePair[],
    required: true,
  },
},

The definition of LabelValuePair is provided below

interface LabelValuePair {
  label: string;
  value: unknown;
}

In my template, I intend to use something like this:

<li v-for="item in items" :key="item.value as string">
  <span>
    {{ item.label }}: <strong>{{ item.value }}</strong>
  </span>
</li>

The issue is that both the ternary operator and the as keyword from Typescript are not recognized as valid syntax by the vue compiler.

Is there a solution or workaround to avoid resorting to something like the following?

setup(props) {
  const castItems = props.items.map((item) => ({
    ...item,
    value: item.value as string,
  }));

  return { castItems };
},

Answer №1

When LabelValuePair needs to be reused and is supposed to contain a string value in a prop, the following generic type should be used:

interface LabelValuePair<T = unknown> {
  label: string;
  value: T;
}

Additionally,

  items: {
    type: Array as PropType<LabelValuePair<string>[]>,
    required: true,
  },

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

The field 'user' is not recognized on the object type WritableDraft

I've set up a redux userSlice to retrieve user data from the store. client/src/redux/features/userSlice.ts import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"; import { User } from "../../interfaces/user&quo ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

Using Vue 3 to have the ability to include multiple composable instances in a single script tag

Currently in the process of revamping our components that are originally built using the Options API. A key point for refactoring from a code-cut perspective is how we handle our multiple modals, each with their own open/close and boolean logic scattered t ...

Error message: The function URL.createObjectURL is not recognized in this context | Issue with Antd charts

Currently, I am working on integrating charts from antd into my TypeScript application. Everything runs smoothly on localhost, but as soon as I push it to GitHub, one of the tests fails: FAIL src/App.test.tsx ● Test suite failed to run TypeError: ...

Tips for incorporating a mail button to share html content within an Angular framework

We are in the process of developing a unique Angular application and have integrated the share-buttons component for users to easily share their referral codes. However, we have encountered an issue with the email button not being able to send HTML content ...

Identify when the user ceases typing in Angular 2

I am currently working on implementing a feature that detects whether the user is typing or not. I need to determine when the user has stopped typing for at least 3 seconds in order to perform certain actions. I have successfully detected when the user sta ...

How to Resolve a Typescript Promise Syntax Error?

I have been working on creating a login authorization system to secure certain routes in an angular application, but I keep encountering a TypeScript error in the auth-guard.service during compilation. Despite my efforts, I am unable to pinpoint the issue. ...

Definition of PropTypes for content in a React navigation drawer

Currently, I am in the process of developing a custom drawer content using this specific guide: const DrawerContent = (props) => ( <DrawerContentScrollView {...props}> <AntDesign name="close" size={32} onPress={() => ...

Why does the name not appear when I first click the button, only 'emit'?

I am attempting to utilize eventemiter in order to send a name when clicking a button, but it doesn't seem to be working as expected. The issue I am facing is that the name is not displayed the first time I click the button, however, if I click it aga ...

What is the best way to explain the generic parameters of a map that has a key based on a property of the value it contains

Is there a way to define the parameters for a Map in such a manner that each key is linked to a value containing the key as a specific property's value? To clarify, consider this example: const example = { 'a': { specialKey: 'a&ap ...

Create a Nuxt component with styling and webpack to display an image sourced from the

I am utilizing styled components to create buttons: import styled from 'vue-styled-components'; const buttonProps = { color: String, br: String, pad: String, bgc: String, bgch: String, icon: String, }; export default styled('bu ...

The entire screen is filled with a background image, but there's an odd margin that seems

I created a div to use an image as a background that covers the entire screen. However, there seems to be a mysterious margin that I can't seem to remove. After examining the code, I couldn't find any indication that I had configured these margi ...

Error: The OOP class value for translateX in the Web Animation API is returning as undefined

I'm currently working on a basic animation project using JavaScript. I have utilized the Animation class from the Web Animation API. My goal is to create multiple instances of this class in order to animate different elements with varying values and r ...

Show mistakes using source mapping (TypeScript combined with Node/Express)

In my Docker container, I have a node instance running express. Whenever I intentionally cause an error in my simple app.ts file, like below: // Start listening for requests app.listen(3000, () => { console.log('Application Service starting!&ap ...

What could be causing the ngOnInit() method to execute before canActivate() in this scenario

When working with route guards, I am using the canActivate() method. However, I have noticed that Angular is triggering the ngOnInit() of my root AppComponent before calling canActivate. In my scenario, I need to ensure that certain data is fetched in the ...

Advanced Layout: Angular Event window:scroll not Triggering

One issue I am facing is that the event gets triggered on some components but not others. For example, it fires as soon as I route to all other components except for the Landing component. Below are my code snippets: <-- Main Component --> <div c ...

Navigating through a node tree and making changes to its configuration and content

Here's the input I have. Some nodes have downlines with multiple other nodes nested inside. data = [ { "user_id": "1", "username": "johndoe001", "amount": "0.00", "down ...

Inertia with Laravel appears to be triggering Vue components to load twice

After creating a Laravel project with Inertia and Vue, I encountered an issue where the code inside my Vue components is executed twice. To demonstrate this problem, I have created a Test.vue, containing the following code: <template> <div> ...

Setting up TypeScript definitions for Azure Media Player in Angular 10: A step-by-step guide

Having difficulty configuring the TypeScript definition for the Azure Media Player in an Angular 10 project. Using the *.d.ts file obtained from the official documentation Attempted setting up the definition using typeRoots in the tsconfig.json file: &quo ...

What is the best way to retrieve paginated data from a simulated JSON server (json-server)?

Looking to return a page using JSON server found at https://github.com/typicode/json-server. The current JSON structure appears as follows: records :[ { id: '2', name: 'k', }, { id:'3', name:'j' } ] Successfully abl ...