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?