Annotating Vue Computed Properties with TypeScript: A Step-by-Step Guide

My vue code looks like this:

const chosenWallet = computed({
      get() {
        return return wallet.value ? wallet.value!.name : null;
      },
      set(newVal: WalletName) {}
}

An error is being thrown with the following message:

TS2769: No overload matches this call.
  Overload 1 of 2, '(getter: ComputedGetter<unknown>, debugOptions?: DebuggerOptions | undefined): ComputedRef<unknown>', gave the following error.
    Argument of type '{ get(): WalletName | null; set(newVal: WalletName): void; }' is not assignable to parameter of type 'ComputedGetter<unknown>'.
      Object literal may only specify known properties, and 'get' does not exist in type 'ComputedGetter<unknown>'.
  Overload 2 of 2, '(options: WritableComputedOptions<WalletName>, debugOptions?: DebuggerOptions | undefined): WritableComputedRef<WalletName>', gave the following error.
    Type '() => WalletName | null' is not assignable to type 'ComputedGetter<WalletName>'.
      Type 'WalletName | null' is not assignable to type 'WalletName'.
        Type 'null' is not assignable to type 'WalletName'.
    44 |     const { wallet, setWallet } = useWallet();
    45 |     const chosenWallet = computed({
  > 46 |       get() {
       |       ^^^
    47 |         return wallet.value ? wallet.value!.name : null;
    48 |       },
    49 |       set(newVal: WalletName) {

I am struggling to understand the issue, but it seems Vue's computed() function expects the return value to be strictly WalletName, while my getter returns WalletName | null.

I attempted to add types in various places, but the error persists. How can I resolve this?

Answer №1

The computed's getter will have its type determined based on the argument of the setter, which in this case is WalletName. However, due to the conditional return statement, the getter's return type becomes WalletName | null, causing a mismatch with the setter's argument and resulting in the error you encountered.

Solution

To resolve this issue, you have two possible solutions:

const chosenWallet = computed({
  get() {
    return wallet.value ? wallet.value.name : null
  },                        👇
  set(newVal: WalletName | null) {}
})

Alternatively, you can adjust the getter to match the type of the setter's argument:

const chosenWallet = computed({
  get() {                                                 👇
    return (wallet.value ? wallet.value.name : null) as WalletName
  },
  set(newVal: WalletName) {}
})

Answer №2

Have you given it a shot?

let selectedWallet: WalletName | null  = computed({
      get(): WalletName | null {
        return wallet.value ? wallet.value!.name : null;
      },
      set(newVal: WalletName) {}
}

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

What could be causing the issue with these overload calls?

Hey there, I've encountered an issue while using createStore. Can someone please guide me on what I might be doing incorrectly? TypeScript error in /workspace/weatherAppTypescript/App/appfrontend/src/redux/store/index.ts(7,31): No overload matches th ...

Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

"Concealing a column in a PrimeNG data table with dynamic columns: A step-by-step

Hi, I'm looking for a way to hide a column in my PrimeNG data table. Is there an attribute that can be used to turn off columns in PrimeNG data tables? .Html <p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]=" ...

What is the best approach to incorporate a refresh feature for a data stream?

I need to implement a function that updates the current list of items$ and allows for awaiting refreshItems(). This is my working implementation: private readStream = new Subject<T[]>(); readStream$ = this.readStream.asObservable(); getItems = (): ...

What should I do to resolve the "Too few arguments to function" issue in Laravel when using VueJS and implementing DOMPDF?

I'm currently developing an application for a Lab using Laravel and VueJS, where I need to generate PDF reports. To achieve this, I have installed DOMPDF. However, when attempting to execute the method in VueJS to open the PDF, I encounter the follow ...

Creating Live Updates with Laravel Sanctum (SPA) - Implementing Private Channel Broadcasting in Real-Time Notifications

In my project, I am using Laravel -v7.x and Vue CLI in two separate folders for Frontend and Backend. I have successfully configured Laravel Sanctum (SPA) Authentication. Now, the challenge I am facing is creating real-time notifications when certain event ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

Mono repo project utilizing Angular 4+ and Typescript, enhanced with Bootstrap styling

Looking for a project to practice with Angular 4+ using Typescript and a Bootstrap template. Hoping for a setup where I can just run npm install and ng serve to start. Any recommendations for mono repos would be highly valued! ...

Using ngbTypeahead to send arguments

I'm utilizing ngbTypeahead for typeahead search feature, and I'm curious about passing parameters to the search function. <input id="typeahead-basic" type="text" class="form-control" [(ngModel)]="model" ...

Ways to pass a class list from a client to a webmethod using AJAX

I have a list of client-side classes in TypeScript that I need to send to a web method. Here is my TypeScript code: class MakeReportData { LocalName: string; FldSi: number; ViewSi:number; TypeName:string ; CheckBoxshow :boolean ; ...

"Implementing type definitions for a function that updates records with nested properties and callback support

I am currently working on a function that updates nested values within a record. I have different versions of this function for paths of varying depths. My main struggle is figuring out how to properly type the callback function used when updating the val ...

Guide to correcting the file path of an external css within the public directory on Express framework

I am facing an issue with loading external CSS files and need some help to fix the path. Despite multiple attempts, I have been unsuccessful so far. Below is my category structure: https://i.stack.imgur.com/sLTcN.png Within the header.ejs file, this is h ...

Reactivity issue with Vue's data property

After reviewing the following code, I am struggling to make the active data property reactive. My goal is to display a div only when hovering over an image. <template> <div> <img @mouseover="showInfo" class="cursor-pointer w-ful ...

Creating a layout of <video> components in vue.js, complete with the ability to rearrange and resize them through drag and drop functionality

Despite trying numerous libraries and Vue.js plugins, I have yet to find one that meets all of my requirements. I am in need of creating a grid of video HTML elements that are draggable and resizable with a consistent aspect ratio of 16:9. Additionally, I ...

Steps to successfully pass a reference from a parent component to a child component that utilizes TouchableOpacity in React Native

I am facing an issue with passing a transitioning ref from a parent Transitioning view to a child component: const transition = ( <Transition.Together> <Transition.In type="fade" durationMs={300} /> <Transition.Change /&g ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Can you please provide instructions on how to obtain the TypeScript definitions file for a specific version of Jquery, such as 3.2.1

As I navigate my way through TypeScript, I find myself in need of accessing type definitions for a jQuery project in Visual Studio. The project currently utilizes jquery version 3.2.1, and I'm on the lookout for TypeScript type definitions for it. Af ...

Populate a div multiple times in Vue by utilizing v-for

Vue may seem like a simple concept, but as a newcomer, I'm still figuring out how to achieve what I want. I've managed to display information from a database query in a div using V-for. However, my goal is to reuse the same div repeatedly by cl ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...