I am new to Vue/Typescript and was struggling with the following error.
I have a class called UploadableFile like this:
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 represents a image file that we can upload. Since the user will be able to modify the dimensions of it, I set the dimensions as a ref. Plus since the price depends on the dimensions, I use a computed Ref calling a function computePrice, that returns a number.
In the main App, I have a function that defines an empty ref like this:
const files = ref<UploadableFile[]>([]);
This variable will contain the files that the user upload when he clicks on a button. Initially it is empty since the user didnt upload anything. When the user clicks on the button, the following functions is called:
function addFiles(newFiles: File[]){
const newUploadableFiles = newFiles
.map((file) => new UploadableFile(file))
files.value = newUploadableFiles;
}
So it transform an array of HTML files to an array of UploadableFile. The transformation of the array works well but the problem arises when we assign this new array to the ref.
files.value = newUploadableFiles;
I got the following error:
Types of property 'price' are incompatible. Type 'ComputedRef' is not assignable to type 'number'.
I feel like the price ref is somehow unpacked but can't figure out a solution except to transform the type of the price like this:
price: ComputedRef<number|any>;
With this, everything works but now the type of price is Any where it should be number.
Any suggestion ?
The generic paramater UploadableFile[] passed into the ref function call is internally unwrapped using the UnwrapRef type, which results in the error.
If you change your files definition to the following:
const files: Ref<UploadableFile[]> = ref([]);
this doesn't happen and the assignment works just fine.