Attempting to implement Vue in a typescript single page application, I encountered a challenge where arrays needed to be displayed on screen in sorted lists. Despite the seemingly simple nature of the problem, none of the examples I came across seemed to work with Typescript. Can someone provide a functional example of how to make Typescript accept a Vue computed function from an array within the Vue data?
I have created an orderedRegions computed function in the Vue configuration. This function is designed to return a sorted version of the "Regions" data object in Vue. The goal is for orderedRegions to output the same list but sorted alphabetically.
computed: {
orderedRegions: function () : Region[] {
function compare(x : Region, y: Region) {
if (x.name < y.name) {
return -1;
}
if (x.name > y.name) {
return 1;
}
return 0;
}
return this.Regions.sort(compare);
}
}
I discovered that when I remove the Typescript elements and insert this code into my compiled javascript file, it does work as intended. However, Typescript fails to compile because the "this.Regions" object is viewed as a non-existent error. It seems that Visual Studio Code expects "this" to refer to the function scope rather than the Vue scope.
Any suggestions on how to satisfy Typescript with this setup?
...additional attempts based on feedback: 1) I attempted using "shorthand" as shown below, but encountered the same issue. "This" refers to the function instead of Vue, resulting in the Typescript error: "Property 'Regions' does not exist on type '{ sortedRegions: () => any; orderedRegions(): Region[]; }"
orderedRegions() : Region[] {
function compare(x : Region, y: Region) {
if (x.name < y.name) {
return -1;
}
if (x.name > y.name) {
return 1;
}
return 0;
}
return this.Regions.sort(compare);
}
2) I also experimented with the arrow function, yet faced the same discrepancy in Typescript:
orderedRegions: () => {
function compare(x : Region, y: Region) {
if (x.name < y.name) {
return -1;
}
if (x.name > y.name) {
return 1;
}
return 0;
}
return this.Regions.sort(compare);
}