TypeScript – Types in Destructuring Assignment – Vue and Vuex

0 0
Read Time:1 Minute, 28 Second

This is very common right now to use TypeScript in JavaScript project.

TypeScript is using static typing so it’s easier to analyse code. Of course some of Front End Developers can say that JavaScript is giving a possibility to omit static typing and it wasn’t created to deliver this kind of functionality however in case when project is getting bigger it’s better to use it.

Vue and Vuex example

I needed to create actions for Vuex.

const actions = {
  async fetchForm({ commit }, payload: string) {
    try {
      const items = payload;

      commit("setItems", payload);
    } catch (e) {
      commit("setItemsError", e);
    }
  },
}

Binding element implicitly has an ‘any’ type.

During compilation of above file and using linter you should see error:

ERROR in /items.ts
24:21 Binding element 'commit' implicitly has an 'any' type.
22 |
23 | const actions = {
24 | async fetchForm({ commit }, payload: string) {

Basicaly we have an error:

Binding element ‘commit’ implicitly has an ‘any’ type.

or in general:

Binding element implicitly has an ‘any’ type.

FIX for – Binding element implicitly has an ‘any’ type.

What we will need to do is add a type for commit which is assigned to variable from destructuring assignment . To do it we need to use this syntax:

{ variable }: {variable: Type}

In case of more variables:

{ var1, var2, var3 }: {var1: Type, var2: Type, var3: Type}

So lets append this to our function. As we know that commit is a Function we are adding Function type to it:

const actions = {
  async fetchForm({ commit }: {commit: Function}, payload: string) {
    try {
      const items = payload;

      commit("setItems", items);
    } catch (e) {
      commit("setItemsError", e);
    }
  },

Destructuring assignment

If you would like to read a bit more about destructuring assignment I’m inviting for my lesson: https://fedojo.com/course/javascript-course/lessons/destructuring-assignment/.

Feel free to leave a comment!

About Post Author

Piotr Sikora

Piotr Sikora Founder of WolePapierowe.com Co-founder of Liderazgo.pl MeetJS Kielce Committee member. JavaScript and Python enthusiast.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

2 thoughts on “TypeScript – Types in Destructuring Assignment – Vue and Vuex

Leave a Reply

Your email address will not be published. Required fields are marked *

© UiCore 2024. All Rights Reserved.