Tips for declaring a non-reactive instance property in Vue.js with TypeScript

I am currently in the process of transitioning my Vue.js components to TypeScript. In accordance with the recommendations provided in the documentation, I attempted to utilize Vue.extend() for my component implementation. The code snippet for my component is as follows:

import Vue from 'vue';

const Component = Vue.extend({
  // type inference enabled
  
  created() {
    // `y` is non-reactive property
    this.y = 20; // TYPESCRIPT THROWS ERROR
  }
  
  data() {
     return {
        // x is a reactive property
        x: 10 
     };
  }

});

In the above example, I have declared property x as reactive and y as a non-reactive property. Despite my efforts, I encountered difficulties in getting type inference to work seamlessly for property y due to the complexities associated with augmentation in TypeScript.

The straightforward approach of using simple object export to define my component resulted in type errors being thrown for both properties x and y.

As a temporary workaround, I am maintaining this file in JavaScript or contemplating migrating my code to vue-class-component which offers better support for handling such scenarios. However, I am hesitant to make the switch to vue-class-component given that it involves introducing an additional library dependency at the project level.

If anyone has insights on how to appease TypeScript in this situation, I would greatly appreciate the guidance.

Answer №1

If you're looking for a straightforward approach, consider the following solution:

  data() {
     return {
        // x is reactive property
        x: 10
     } as any as { x: number; y: number };
  }

However, keep in mind that this method necessitates explicitly defining all properties of data.


Another option is to utilize the following helper function:

function withNonReactive<TData>(data: TData) {
    return <TNonReactive>() => data as TData & TNonReactive;
}

Here's how it works:

  data() {
     return withNonReactive({
        // x is reactive property
        x: 10
     })<{
        // non-reactive properties go here
        y: number
     }>();
  }

Answer №2

To eliminate TypeScript errors, a helpful approach is to declare the following property:

data() {
    return {
       nonReactive: {} as any
    }
}

Then, you can simply add your non-reactive properties to this object in the created() method.

created() {
    this.nonReactive.foo = {}
}

Another technique that I have yet to fully explore involves creating a typescript shim file specifically for your component.

Answer №3

Alternative Approach without Using Function Wrapper


Vue.extend({
  data() {
    const dynamicData = {
      title: 'Captain Jack Sparrow',
    }

    return dynamicData as typeof dynamicData & {
      additionalProperty: string;
    }
  },
})

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 sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

Using checkboxes in an Express application

Currently, I am working on the task of parsing checkbox values into an array using express/ejs. Users are required to fill out a form and select checkboxes as shown below: Answer: Checkbox: The goal is to create two arrays from the input data: answer = ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Unlock the secrets of creating a pop-up with qtip

I am working on qtip code that generates a popup when a specific link is clicked. I'm wondering if there's a way to use jQuery to determine if the link with the id "test2" has been clicked or not. Thank you, James <ul> <li><a id= ...

The Star Rating System fails to update accurately after hiding the Radio Buttons

I followed a tutorial to set up a Star Rating System Everything was working fine on the SHOW PAGE and the INDEX PAGE until I decided to hide the Radio Buttons and use the corresponding labels to submit the value. I encountered an issue where the JavaScrip ...

You do not have permission to access the restricted URI, error code: 1012

What is the best solution for resolving the Ajax cross site scripting issue in FireFox 3? ...

Updating state in React without providing a key prop is a common issue, especially when

Currently, I am working on implementing a Radio Group where I want the radio button's checked value to update when another button is clicked. In the example provided below, it seems that the desired effect can only be achieved using the "key" prop. Is ...

I'm just getting started: an image carousel featuring a unique twist with random quote overlays, but there's a catch - it only activates on the very first image... what comes next?

After successfully displaying the generator over the first image, I encounter a problem with the second and third images where it seems to disappear. However, upon cycling back to the first slide, the generator reappears with a different quote. I've a ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Utilizing the multer Express middleware in a standalone file

I successfully moved a basic middleware (isAuthenticated) to an external file, but I'm facing challenges transferring my multer upload. Although I recently learned how to separate them into different files, this task seems more complex. routes/index. ...

Utilizing Generics in TypeScript to Expand Abstract Classes

How can I define the property eventList in the class ImplTestClass to be an array with all possible values of AllowedEvents, while extending the class TextClass that accepts T? I'm stuck on this one. If anyone can provide guidance on how to achieve t ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

What is the method of updating content on a webpage without altering the page itself or using hashed URLs?

I have a good understanding of how to update webpage content through AJAX and loading remote content. However, I recently came across UStream's innovative new layout. When you click on any video, not only does the content change seamlessly without rel ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

How to organize initial, exit, and layout animations in Framer Motion (React) tutorial?

Currently, I am utilizing framer-motion library for animating a change in grid columns. This is the objective: Within the grid container (#db-wrapper), there are nine buttons arranged. https://i.stack.imgur.com/61pQqm.png When the user switches to the ...

Utilizing jQuery to retrieve data from a JSON object with a nested array

After making an API call to Google Translate, the following data was returned: { "data": { "detections": [ [ { "language": "en", "isReliable": false, "confidence": 0.051902372 } ] ] } } In order to access the "language" ...

Error: Unable to load chunk.js in Angular 7

After upgrading to Angular 7, I've been diving into the world of Lazy loaded modules. However, despite my efforts, I can't seem to find #chunk.js anywhere in the network tab when I click on components within the lazy loaded module. Even when Con ...

byte sequence displays as binary data (angular + express)

I've been working on pulling files from a back-end Node.js / Express server and displaying them in an Angular front-end. Despite trying different methods, I keep facing the same issue - the data displayed at the front-end appears as a bytestring. Even ...