Array map to new type in TypeScript

How to array map to a different type in Typescript


In my recent Nextjs project, need to shape object array to a different type.

Mapping through the entire array in my arrow function and return the new object.

Even though the return statement work. The type is still unknown. So, I have to covert the result into array of my type.

Mapping Array Type

export type LatestInvoiceType={
id:number;
amount: number;
customer:{
name:string;
email:string;
image_url:string;
}
}

New Type

 export type LatestInvoice = {

id: string;
name: string;
image_url: string;
email: string;
amount: string;
};

Solution to the problem

Here is my solution to the problem

    const latestInvoices  = invoices.map(invoice =>  {
      return{
      id:invoice.id.toString(),
      amount:invoice.amount.toString(),
      name:invoice.customer?.name,
      email:invoice.customer?.email,
      image_url:invoice.customer?.image_url
      };
    }) as LatestInvoice[] ;

Use props in script setup-Vue 3

How to create props in script setup in Vue 3


script setup

Script setup replace the regular script in Vue3 . We can import component and use without registering in the component section.

Following is simple Vue home component

<template>
  <div class="page-index">
    <Logos />
 
  </div>
</template>
<script setup>
import Logos from '../components/Logos.vue'
</script>

<style>
.page-index {
  padding-top: 60px;
  text-align: center;
}
</style>

Props

Props are way to pass data to the child from parent. Vue 3 come with inbuild defineProps method for defining props. We need not to import this method.

<script setup>
const props = defineProps({
  data: {
    type: [Object],
  }
})

Use props in script setup-Nuxt3

How to create props in script setup in Nuxt3


script setup

Script setup replace the regular script in Vue3 . We can import component and use without registering in the component section.

Following is simple Vue home component

<template>
  <div class="page-index">
    <Logos />
 
  </div>
</template>
<script setup>
import Logos from '../components/Logos.vue'
</script>

<style>
.page-index {
  padding-top: 60px;
  text-align: center;
}
</style>

Props

Props are way to pass data to the child from parent. Vue 3 come with inbuild defineProps method for defining props. We need not to import this method.

<script setup>
const props = defineProps({
  data: {
    type: [Object],
  }
})

Computed property in Vue3 script setup

How to use computed lifecycle method in new Vue 3 script setup.


Familiar with Vue 2 or earlier ? You should have love the computed property. It keep track of the changes on reactive variables.

Few recommendations, if you are a beginner in Vue

Script setup and Computed

<Script setup> is here to simplifying the creation of component in Vue3. It let us import and use component without registering and create method as regular TS/JS arrow function.

<script setup>

In Vue 3 setup, every data component that are meant to use in template should export from the setup function.

In our example a Vuex 4 store used to store the count, and perform increment.

<template>
  <div class="home">   
   <button @click="this.$store.dispatch('setCount',1)">Add</button>
  {{count}}
  </div>
</template>

<script setup>
import {useStore} from 'vuex' 
import { computed,} from 'vue';
const store=useStore();
const  count= computed(() => store.state.count)   
</script>

In the setup we created object for store and a computed property and note that the define component no longer needed.

In the button click accessed the store action and thus the global state will change. Using the useStore hook let us access the state within the component.

Store

Our store look like

import { createStore } from 'vuex'
export default createStore({
  state: {
    count:10
  },
  mutations: {
    increment(state,hit){
      state.count+= hit;
    }
  },
  actions: {
    setCount({commit },num:number) {
      commit('increment',num)
    }
  },
  modules: {
  }
})

Computed property in Vue3 Composition API setup

How to use computed lifecycle method in new Vue 3 .


Familiar with Vue 2 or earlier ? You should have love the computed property. It keep track of the changes on reactive variables.

Few recommendations, if you are a beginner in Vue

Composition API and Computed

This is the default in Vue 3, so it is better to under stand the new setup. The old one too valid in Vue 3.

Setup

In Vue 3 setup, every data component that are meant to use in template should export from the setup function.

In our example a Vuex 4 store used to store the count, and perform increment.

<template>
  <div class="home">
   
   <button @click="this.$store.dispatch('setCount',1)">Add</button>
  {{count}}
  </div>
</template>

<script>
import {useStore} from 'vuex' 
  import { computed,defineComponent } from 'vue';
export default defineComponent({
 
  setup() {
    const store=useStore()
    const count=computed(()=>store.state.count)
    return{
      store ,
      count
    }
})
</script>

In the setup we exported the computed function using arrow syntax.

In the button click we accessed the store action and thus the global state will change. Using then useStore hook let us access the state within the component.

Store

Our store look like

import { createStore } from 'vuex'
export default createStore({
  state: {
    count:10
  },
  mutations: {
    increment(state,hit){
      state.count+= hit;
    }
  },
  actions: {
    setCount({commit },num:number) {
      commit('increment',num)
    }
  },
  modules: {
  }
})

Auto import components in Nuxt3

How to auto import components in nuxt


Nuxt 3 is hybrid framework that work on the top of Vue3 , which used to reactive single page web apps. Nuxt 3 has many performance upgrade as well as structural changes. One of them is Plugins.

Components and nuxt-config

Components are basic building blocks of a Vue app, just like other frameworks such as React or Angular.

In Nuxt3 one of the cool thing I love is the auto import feature, which can be configured in nuxt-config.ts . We can add more component locations in the components array.

 components: [
      '~/components/',
  ]

In the any component you can godhead and simply use it as

<template>
  <div class="page-index">
    <Logos />
  </div>
</template>

Vuex 4 require plugin in Nuxt3

How to setup Vuex4 store in Nuxt3


Nuxt 3 is hybrid framework that work on the top of Vue3 , which used to reactive single page web apps. Nuxt 3 has many performance upgrade as well as structural changes. One of them is Plugins.

Vuex 4

Vuex is the official store (for sharing data among component without using props) for Vuejs apps. Vuex 4 is the store for Vue3 applications and Nuxt3.

Nuxt3

To getStarted with Vuex4 in Nuxt3 , we need a vue plugin, since there no official @nuxt module for the latest store. Pinia does have a module for Nuxt, and it work well.

Plugin

Create vuex.ts in plugins directory with following content.

import { defineNuxtPlugin } from '#app'
 
import {store} from  '@/store/store' authors

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(store)
})

Store

We can create a regular vuex store as follows

import { createStore } from 'vuex'

export const store = createStore({
    state() {
        return { count: 0}
    }
})

Nothing special about the store. Let’s access it through the component.

<template>
  <div>
   {{store}} 
 <NuxtWelcome/>
    
  </div>
</template>

<script >
   export default({
     data(){
      return {
          store: this.$store.state.count
      }
    }
  })
</script>

Reset a form using template ref in Vue3

Resetting form fields using Vue3 template refs.


Vue 3 is a progressive framework for web development, this opensource project is a power tool in web developer kit. It’s fast, lightweight and easy to learn. Version 3 has many performance upgrade from Vue 2.

Template refs

In addition to reactive ref vue also provide template ref which allow us to access the DOM element directly. This will allow us locate a an element in the template and perform operations such set focus.

Form and ref

To set a ref for form input we have to name a ref using ref=”nameref” (template) and can access it using this.$refes.nameref. We can call focus function to focus the field.

We can set a ref to form or input field, when a ref is set to input , the form ref not work. To set a ref to form use ref=”myForm”.

      <el-form
        label-width="80px"
        size="mini"
        ref="ruleForm"
      >

We can perform reset field action using a handler, in @click set the following handler.

    resetForm() {
      this.$refs.ruleForm.resetFields();
    },

TypeScript Vuex 4 store setup

How to setup a TypeScript Vuex store in Vue3


Vue 3 is a progressive framework for web development, this opensource project is a power tool in web developer kit. It’s fast, lightweight and easy to learn. Version 3 has many performance upgrade from Vue 2.

Vuex 4

Vuex 4 is the official store for managing global state in Vue 3 app. Setting up a JS store setup is so easy. Let’s set up a store in TS, which require different approach

Add store to project

Fire the vue add vuex command from the root of the project, it will install the dependencies and create a blank store for us.

TS store

We need few interface, Injection keys to create and configure store. To simplify the store we can put everything in a single file , store.ts / index.ts.

// store.ts
import { InjectionKey } from "vue";
import { createStore, Store } from "vuex";

export interface State {
  count: number;
}

export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
  state: {
    count: 1,
  },
  mutations: {
    },
  actions: {
  },
});

Global store configuration

To make the store available to all components, in the main.ts import and use the it as plugin.

import {store} from './store'
 const app = createApp(App)
app.use(store).use(router).mount('#app')

In a component

In a component we can access the store using Vuex function, useStore.

<script setup lang="ts">
import {useStore} from 'vuex'
 const store = useStore(App);
 </script>
<template>
{{store.state.count}}
</template>

TS plugin error Element Plus

How to fix type error in element-plus Typescript project


Element Plus is a Vue 3 UI library which help developers and UI designers quickly build apps and components. Most of the parts of the library coming from the Chinese contributor and has large user base.

Element Plus is a good choice when developing web and desktop apps.

Plugin error

TypeScript Error in Element-Plus (Vue3)

When using Element-Plus using plugin in Vue3 and Typescript, you may have encounter parameter app has an ‘any’ type error. This will happen when you configure TS in an existing Vue project.

Solution

To solve the issue provide a type in the plugin function. For our quick fix it can be any


export default (app:any) => {
  app.use(ElementPlus)
}