⚠️ This lesson is retired and might contain outdated information.

Access State by using Vuex getter functions with TypeScript

Share this video with your friends

Social Share Links

Send Tweet

Accessing state directly can be ok for some cases, but in others we need another representation of state.

This lesson will show you how Vuex getters solve that issue and how to type-safe these getters with TypeScript using the @Getter decorator.

We're going to add a checked property to the items in a todo list. In that way, we're going to split it into checked items and then unchecked items. For that, let's go to the todos TS file, where we have the state, and add a couple more of items with a check property.

Go shopping, and get her cat. We see that TypeScript is complaining about the check property, because it doesn't exist in the todo model. Let's add it there, check:boolean. If we go back, then we see it's not complaining anymore.

We see in the right side the three items are there. Let's go now to getters. Getters are just functions that receive the state as the first parameter. An important point is that by default, they are typed as any, but we can type them by using the getter tree from Vuex. Let's import it first.

Then let's type it using the getter tree, which is a generic that has two parameters. The first one is a state, and the second, the root state that we will see in another lesson. If we check it now, we see that it's typed as a state. We get type safety.

Moving on, we want to return here an array of todos that are not checked. We can use the filter function for that. The same for the DOMs, which we return the checked ones. Don't forget to add the getters to the Vuex store instance. Let's go to the index.ts file, add the getters to the Vuex store, and import them.

Now, it's time to go back to the app component and use there the getter decorator instead of the state. It works the same way. It will bind the variable name to the getter from our store. Let's do the same for the DOMs one.

Let's go up to the template and add there a heading for the todo list, and duplicate it, so we can do the same for the DOMs one. Now, replace it in the before, and that's it. Save it, and see the lists now are splitted as intended.