Having trouble typing computed values in Vue Composition API with TypeScript?

I'm attempting to obtain a computed value using the composition API in vue, and here is the code I am working with:

setup() {
  const store = useStore();
  const spaUrls = inject<SpaUrls>('spaUrls');
  const azureAd = inject<AzureAd>('azureAd');
  const account: AuthenticationAccount = computed<AuthenticationAccount>(() => store.state.authentication.account);

  watch(() => account, (newValue, oldValue) => {
    if (oldValue.loading && !newValue.loading && !newValue.hasAccount) {
      // no account so redirect to unauthenticated page
      window.location.href = spaUrls.accessDenied;
    }
  });

  store.dispatch('authentication/authenticate', azureAd);
},

However, it's encountering compilation errors as follows:

Type 'ComputedRef' is missing the following properties from type 'AuthenticationAccount': hasAccount, loading

If I change it to

const account = computed<AuthenticationAccount>(() => store.state.authentication.account); 

It then fails with the following errors:

Property 'loading' does not exist on type 'ComputedRef'
Property 'hasAccount' does not exist on type 'ComputedRef'

How should I define the type for the account variable?

Answer №1

Upon further investigation, I discovered that the computed ref includes a .value property that holds the typed variable. To ensure functionality, I updated my code as shown below:

const account = computed<AuthenticationAccount>(() => store.state.authentication.account);

watch(() => account.value, (newValue, oldValue) => {
  if (oldValue.loading && !newValue.loading && !newValue.hasAccount) {
    // no account so redirect to unauthenticated page
    window.location.href = spaUrls.accessDenied;
  }
});

In addition to the above approach, I also found that

watch(account, (newValue, oldValue) => {
  if (oldValue.loading && !newValue.loading && !newValue.hasAccount) {
    // no account so redirect to unauthenticated page
    window.location.href = spaUrls.accessDenied;
  }
});

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 on simulating rxjs/Websocket in angular for performing Unit Testing

I have developed a service that manages websocket communication with a server and I am looking to create unit tests for it. However, I am facing challenges in mocking rxjs/Websocket. While searching for a solution, I came across a similar question here, b ...

Electron does not have the capability to utilize Google's Speech to Text engine

I am trying to connect my microphone with the Google Speech to Text engine. I came across this page and copied the code into my renderer.ts file, uncommented the lines with const, but when I run it, I encounter an error at line 7 (const client = new speech ...

Traverse the elements of a BehaviorSubject named Layer_Template

I am currently facing an issue with displaying data from my BehaviorSubject. I have come across a way to iterate through a BehaviorSubject using asyncpipe which subscribes to the Observable SERVICE todo.service.ts @Injectable() export class TodoService ...

Passing data to a child component using Context in React is not working

I have a parent component where I am storing data in an array of objects and then passing it to another component through Context. Here is how my parent component looks: export type HistoryData = { input: string; date: string; ...

Combining Two External Components in VueJS: A Step-by-Step Guide

I am currently utilizing the Form Tags components from the bootstrap-vue framework. My goal is to integrate the vue-simple-suggest component (obtained via npm) with form tags in order to suggest words related to the user's query. Users should be able ...

Having trouble getting material-ui container to work with custom breakpoints in TypeScript?

Currently, I am exploring material-ui and typescript within my educational project. However, I have encountered a perplexing issue for which I am seeking assistance. In this project, I utilize custom breakpoints in the material-ui theme settings. import { ...

Tips for setting up a queue system for alert messages in Vue.js with Vuetify

Seeking assistance with modifying my code to handle multiple alerts and implement a customizable timeout duration. Any advice on how to approach this would be greatly appreciated. ~/store/toast-messages.js export const state = () => ({ color: '&a ...

Is there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...

Ionic - Deleting an item from local storage

Currently, I am implementing local storage for my Ionic application. While I can successfully add and retrieve data from local storage, I encounter an issue when trying to delete a specific object - it ends up removing everything in the database. Moreover, ...

NPM is lacking in providing sufficient guidance on resolving dependency problems

While attempting to incorporate Typescript into my Gatsby project after the fact, I encountered a cryptic error from NPM: npm ERR! code EOVERRIDE npm ERR! Override for @types/react@* conflicts with direct dependency npm ERR! A complete log of this run can ...

Combining indexed types with template literals -- add a prefix to each key

Start with type A and transform it into type B by adding the prefix x to each key using Typescript's newest Template Literal Types feature: type A = { a: string; b: string; }; // Automatically generate this. type Prefixed = { xa: string; xb: ...

in Vue.js, extract the style of an element and apply it to a different element

Currently, I am using VUE.js 2 in my project. Here is my website's DOM structure: <aside :style="{height : height()}" class="col-sm-4 col-md-3 col-lg-3">...</aside> <main class="col-sm-8 col-md-9 col-lg-9" ref="userPanelMainContents" ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

How can one create a constant in VueJs that can be easily accessed throughout the entire application?

In my Vue.js application, I am able to create a constant through a store, but I have reservations about this practice. Can anyone suggest alternative methods to achieve the same outcome? ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Best approach to inform pages about a variable update in Ionic

Imagine a scenario where we have a page called ListItemPage displaying a list of items: Within the ts file, there is a variable defined as items: any = []; In the html file, we find <ion-item *ngFor="let item of items"> Users can click on a (+ ...

Calling GraphQL mutations in ReactPGA

I encountered a 400 Error when making a call from the client to server, and I'm not sure where to start troubleshooting. Oddly enough, when I only include the "id" parameter in the request, everything works fine. However, as soon as I add the additio ...

Is there a way to prevent prettier from automatically adding a new line when formatting HTML tags with ">"?

While navigating through the Prettier extension in Vscode, I am struggling to find a way to disable a specific scenario. In particular, I am having trouble with the formatting of an html tag. Below is a snippet of code that requires some adjustments whene ...

What is the best way to create hover effects on buttons in Vue.js 3?

I'm currently developing a calculator to practice my Vue.js 3 skills (I am new to vue). I've successfully implemented the basic features, but now I'm exploring how to incorporate hover animations on the buttons. Specifically, I want to diffe ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...