A Vue object with dynamic reactivity that holds an array of objects

I've experimented with various approaches, but so far I've only managed to get this code working:

// This works
<script setup lang="ts">
import { reactive } from 'vue'
import { IPixabayItem } from '../interfaces/IPixapayItem'
const imageList: IPixabayItem[] = []
const foundImages = reactive(
    {
        images: imageList
    }
)
</script>

I'm trying to find a way to eliminate the use of the 'imageList' constant and instead initialize the 'IPixabayItem[]' directly inside the reactive object. However, I haven't been able to make that work during transpilation.

// This doesn't work
<script setup lang="ts">
import { reactive } from 'vue'
import { IPixabayItem } from '../interfaces/IPixapayItem'
const foundImages = reactive(
    {
        images: IPixabayItem[] = []
    }
)
</script>

Any help would be greatly appreciated.

Answer №1

To set IPixabayItem[] as the generic parameter of reactive and provide an empty array for images, you can do the following:

const foundImages = reactive<{images: IPixabayItem[]}>({
    images: []
})

Try it out on Playground


Another approach is to use the as keyword like this:

const foundImages = reactive({
    images: [] as IPixabayItem[]
})

Give it a try on Playground

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

Vuetify's v-text-field not properly aligning text to the center

The alignment of the text in v-text-field is causing issues for me, as I am unable to center it. Despite attempting various solutions, I have not been successful. 1. <v-text-field type="number" class="mr-2 text-center"></v-te ...

What is the best way to handle waiting for an API call in JavaScript export?

In my Vue app, I've set up my firestore app initialization code as shown below: if (firebase.apps.length) { firebase.app() } else { firebase.initializeApp(config) } export const Firestore = firebase.firestore() export const Auth = firebase.auth() ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

What is the best way to refresh the snapshots in my React/TypeScript project?

I am working on a React/TypeScript project that utilizes the Jest testing framework. Occasionally, after making changes to my code, Jest will compare it to the snapshots and generate an alert requesting me to update them. However, there are instances where ...

What is the conventional method for incorporating style elements into Vue.js components?

Imagine I have a Vue component with data retrieved from an external API, containing information about various books: data: () => ({ books: [ {name: 'The Voyage of the Beagle', author: 'Charles Darwin'}, {name: &ap ...

The v-tabs component in Vuetify seems to be unable to fill 100% of the available

When using the v-tabs component, I noticed that it doesn't take up 100% of the height. Upon further inspection, I found that all the tab items (tab contents) are wrapped inside a <div class='v-tab__items'> your content </div ...

Is it possible to remove a specific directory from the webpack build configuration in a vue-cli-3 setup?

After spending 3 hours adding the line: exclude: ['./src/assets/sass'] in 20 different places, I am seeking guidance on where it should actually be placed. Below is my current setup for the css-loader (util.js): 'use strict' const path ...

The result of comparing with `instanceof` in TypeScript

class Department { name: string; constructor(n: string) { this.name = n; } describe(this: Department){ console.log('department: ' +this.name); } } const frontend = new Department('frontend'); frontend.describe(); con ...

Generate sample data within a fixture

Currently, I am in the process of working on a project that involves creating users and conducting tests on those users. To generate user data such as first name and last name, I am utilizing the faker tool. My goal is to create a user with these generated ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

The error message "jsPDF is not defined in Laravel using Vuejs and bootstrap-table-vue"

I encountered an issue when attempting to export a Bootstrap table in Vue as a PDF format. The error message I received was: app.js:100649 Uncaught ReferenceError: jsPDF is not defined at jQuery.fn.init../node_modules/tableexport.jquery.plugin/tableEx ...

Setting up child routes can be easily accomplished by following these steps

I've been exploring the functionality of child routes within VueJS. My assumption was that setting up a news overview with links to individual news items and using a child route would allow me to view each item separately. However, it's not worki ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

The function signature '({ articles }: Props) => JSX.Element' does not match the type 'NextPage<{}, {}>'

Recently, I've decided to delve into the world of React.js and Next.js after being familiar with Vue.js. Encountering a peculiar typescript error has left me scratching my head, but surprisingly, the code actually compiles despite Visual Studio Code w ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

The argument provided, 'Item', cannot be assigned to the parameter, 'string'. TS2345 error encountered

Encountering an issue with type 'string'. Error code TS2345 Problem: Argument of type 'Item' is not compatible with parameter of type 'string'. TS2345 filter(resortList:ResortResult[], selectedFilters:SelectedFilters) { ...

The issue I'm facing with the change handler for the semantic-ui-react checkbox in a React+Typescript project

Hey there! I'm currently facing an issue with two semantic-ui-react checkboxes. Whenever I try to attach change handlers to them, I end up getting a value of 'undefined' when I console log it. My goal is to retrieve the values of both check ...

Tips for designing a multi-level dropdown navbar

I am currently facing an issue with designing a navbar. I am aiming for Multi-Level Dropdowns, but whenever I click on More Services, it automatically closes the main dropdown menu. I have experimented with various approaches, but none of them seem to be ...

Accurate TS declaration for combining fields into one mapping

I have a data structure called AccountDefinition which is structured like this: something: { type: 'client', parameters: { foo: 3 } }, other: { type: 'user', parameters: { bar: 3 } }, ... The TypeScript declaration ...

Error: Unable to iterate over data.data due to its type

I am attempting to fetch images from the woocommerce API and here is the code I am using: this.config.getWithUrl(this.config.url + '/api/appsettings/get_all_banners/?insecure=cool') .then((data: any) => { this.banners = data.data; consol ...