Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile:


export class UploadableFile {
  file: File;
  dimensions: Ref;
  price: ComputedRef<number>;
  ...
  constructor(file: File) {
    this.file = file;
    this.dimensions = Ref({width: file.width, height: file.height})
    this.price = computed((): number => {
      return computePrice(this.dimensions);
    });
  }
}

This class is designed to represent an image file that can be uploaded. To allow users to modify the dimensions, I used a ref for dimensions. Additionally, since the price calculation relies on the dimensions, I implemented a computed Ref that calls the computePrice function to retrieve a number.

In my main App, I have a function that initializes an empty ref as follows:


const files = ref<UploadableFile[]>([]);

This 'files' variable will store files uploaded by the user upon clicking a button. Initially, it's empty until a user uploads something. When the button is clicked, the following function is triggered:


function addFiles(newFiles: File[]){
  const newUploadableFiles = newFiles.map((file) => new UploadableFile(file));
  
  files.value = newUploadableFiles;
}

This function converts an array of HTML files into an array of UploadableFile objects. While the array conversion functions smoothly, the problem arises when assigning this new array to the ref.


files.value = newUploadableFiles;

The error message received was:

Types of property 'price' are incompatible. Type 'ComputedRef' is not assignable to type 'number'.

I suspect the price ref may be getting unpacked, but I'm unable to find a solution other than changing the price type like this:


price: ComputedRef<number|any>;

Although this change resolves the issue, the price type becomes Any instead of number. Any suggestions?

Answer №1

When the ref function is called with a generic parameter of UploadableFile[], it is internally unwrapped using the UnwrapRef type, resulting in an error.

To avoid this issue, make sure to define your files variable as follows:

const files: Ref<UploadableFile[]> = ref([]);

By making this change, you can ensure that the assignment works correctly without any errors.

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

Accessing properties of objects using specific keys

In my coffeescript code, I am attempting to retrieve the keys from an object where the key matches a specific value. However, in addition to the object's own properties, I am also getting function properties in my result. This issue is causing an err ...

How can you use JQuery to assign a single function as an onClick handler for multiple radio buttons?

I have a custom function named handleOnClickRadio(i, j);, and multiple radio buttons with the IDs in the format of id="something-radio[i][j]". These radio buttons are all contained within a table labeled "bigtable". Is there a way to link the function han ...

Generating a file using buffer information in node.js

From the front-end client side, I am sending a file to the server. On the server-side, the data received looks something like this: { name: 'CV-FILIPECOSTA.pdf', data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 6 ...

Troubleshooting: Vue.js Component template not displaying items with v-for loop

I recently implemented a method that calls an AJAX request to my API and the response that it returns is being assigned to an array. In the template section, I am using the v-for directive to display the data. Surprisingly, it only renders once after I mak ...

Error: The 'Window' object is not defined. The use of Client in NextJS13 is not

I've been attempting to integrate NextJS 13 with react-leaflet, but I keep encountering the error "window is not defined" when running my component. I attempted using the "use client" declaration at the beginning of the file and adding a check for "ty ...

Obtain image URL from object properties using AngularJS

Just starting out with Angular JS and I have a question. I'm currently working on a project and I have a solution in mind, but I was wondering if there's a more "angular-esque" approach that I could take. The idea is for each videoid, there wou ...

Update a particular package using Node

Is there a way to update Browser-sync without updating all my node packages? I need the version with the Browser-sync GUI, but I don't want to update everything else. ├─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Unable to retrieve shared schema from a different schema.graphql file within the context of schema stitching

In my project, I have a user schema defined in a file named userSchema.graphql; id: String! userName: String! email: String! password: String! } In addition to the user schema, I also have separate schema files for login and register functionalit ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. ...

What could be causing req.params to come back as undefined?

I have reviewed two similar questions here, but none of the suggestions in the comments seem to be resolving my issue. app.get('/:id', function(req,res) { console.log(req.params.id); }); app.get('/:id', function(req, res) { db.que ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

What is causing this code to run immediately upon the addition of Promise logic?

The coding scenario written below was supposed to have two 4-second delays. However, when the code is run, it executes immediately. It seems that there might be a lack of understanding on my part regarding some basic concept, or perhaps there's a hidd ...

gmap3 has encountered an error: undefined is not a valid function

I am working on a WordPress site and trying to integrate a Google map into the contact page. However, I'm encountering an error Uncaught TypeError: undefined is not a function in the JavaScript console. Below is the code snippet causing the issue, can ...

Tips for implementing automatic line wrapping in a PDF document using React-PDF

I am experiencing an issue with a PDF rendering where very long words are not wrapping onto a new line, instead overflowing the container and disappearing off the page. Below is the setup causing this problem. The styles are listed followed by the actual ...

Retrieving a PHP variable from HTML without using a form

Is there a way to pass a variable from HTML to PHP without using a form and the traditional post or get methods? I have tried using the code provided, but I am unable to access the value of the 'buy1' variable in PHP. Is there a way to achieve th ...

Guide on implementing "Displaying 1 of N Records" using the dataTables.js framework

let userTable = $("#user_table").DataTable({ 'sDom': '<"row-drop"<"col-sm-12 row"lr>><"row"t><"row-pager"<"col-sm-12 col-md-5"i><"col-sm-12&qu ...

Adjust the position of the IMG to the left side

Struggling with some code and need some assistance: <script> function run() { document.getElementById("srt").value = document.getElementById("Ultra").value; } </script> <script> function ru ...

Tips for bringing in an npm package in JavaScript stimulus

Looking to utilize the imageToZ64() function within the zpl-image module. After installing it with: npm install zpl-image I attempted importing it using: import './../../../node_modules/zpl-image'; However, when trying to use the function like ...

The conditional statement for multiplying in JavaScript

I have a JavaScript function that selects a report number based on multiple parameters (2 checkboxes, 3 dropdown fields), and the current implementation involves a complex conditional statement as shown below: switch(ReportNumDrop) { case 0 ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...