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

Guide to modifying the column color in Chart.js

Link to my codepen project: Check it out here let ctx = document.getElementById('myChart').getContext('2d'); let chart = new Chart(ctx, { // Type of chart being created type: 'bar', // Data for the dataset data: { ...

The Consequences of Using Undeclared Variables in JavaScript

What is the reason behind JavaScript throwing a reference error when attempting to use an undeclared variable, but allowing it to be set to a value? For example: a = 10; //creates global variable a and sets value to 10 even though it's undeclared al ...

What is the best way to implement this ajax preloader?

<script type="text/javascript"> $(document).ready(function() { $('#loading') .hide() .ajaxStart(function() { $(this).show(); }) .ajaxStop(function() { $(this).hide(); }); } ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Struggling to navigate the world of JavaScript and find the sum of odd numbers?

Currently facing a roadblock with a codewars exercise and in need of some assistance. The exercise involves finding the row sums of a triangle consisting of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 ...

Enhance user experience with Bootstrap by automatically adding a frame around a card upon clicking

Hello everyone! I am a beginner in the Angular/Web Development world and I am currently working on improving my HTML/CSS skills. While using Bootstrap in my Angular project, I ran into a challenge that I couldn't figure out on my own. I have implement ...

I encountered an issue trying to animate an OBJ file in Three.JS, even after successfully loading it into the browser

I have encountered a challenge with scaling and animating an object loaded into my web browser using WebGL. The issue arises when attempting to include animation code within the render( ) loop function, specifically with the 'object' variable whi ...

How to retrieve values from dynamically generated text boxes using ng-repeat in AngularJS

When using ng-repeat, I am able to display textboxes related to each item. Upon clicking the SaveAll button, I intend to retrieve all textbox values based on ITEM ID and save them to the database. <tr> <td> <table ng-repeat="item in ...

Create a full type by combining intersecting types

I have multiple complex types that are composed of various intersecting types. I am looking to extract these types into their final compiled form, as it would be useful for determining the best way to refactor them. For example, consider the following: ty ...

Troubleshooting ASP.NET Ajax Error Code 0

Starting from scratch with asp.net and hoping to incorporate infinite scrolling using jQuery Ajax and ASP.NET MVC. Here's the progress so far: <div id="container"></div> <div id="progress" style="display:none"> <h4>Loading ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

MariaDB won't generate JSON output for a column that has a JSON data type

Currently, I am utilizing MariaDB and phpMyAdmin to effectively manage my database. Within one of my tables, I have a specific field that is defined as type json, or alternatively longtext. However, whenever I execute a SELECT query using JSON_EXTRACT(fiel ...

Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments. For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types: this.F ...

Is it possible to append an "index" to a database field using Express, Loopback, or NodeJS?

Currently, we are utilizing the Express/Loopback Framework for our backend. I am currently working on ensuring that indexes on certain fields in models are properly created in MongoDB. Is there a way to utilize meta-tags within the models so that DataJuggl ...

Is there a way to disable a dropdown menu when clicking on a different one?

[![ Dashboard Admin Admin Profile Change Password Doctors Doctors List Doctors Appointments Doctors Requests Add a Doctor Patients ...

Guide on testing a function with a dependency in Angular through unit testing

Attempting to dive into unit testing, I have grasped some of the basics. However, my current challenge lies in testing a method within my code. This particular method involves calling a function from oidc-client.js that handles user sign-ins. My spec fi ...

How can you include a multi-layered array within another multi-layered array using TypeScript?

If we want to extend a two-dimensional array without creating a new one, the following approach can be taken: let array:number[][] = [ [5, 6], ]; We also have two other two-dimensional arrays named a1 and a2: let a1:number[][] = [[1, 2], [3, 4]]; let ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Executing system commands using Groovy is a breeze

One of the scripts I have is a sample.js script that allows me to view files located on the server myHost. It works perfectly: var exec = require('ssh-exec') var v_host = 'myHost' exec('ls -lh', { user: 'username&apo ...

Unraveling the Mysteries of AngularJS in a Tutorial Snippet

After reading through the enlightening theory snippets in Step 3 of AngularJS Tutorial, one particular passage piqued my curiosity: The scope, which connects our controller and template to create a dynamic view, is not isolated within its own bounda ...