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[] ;

How to create a colorful doughnut in Vuejs

How to create a a colorful doughnut chart in Vuejs


In this post you will learn

  • Create a TS component
  • Create props
  • Mixin multiple props and function
  • vue-chartjs
  • chartjs doughnut chart

Vue-Chartjs

Vue-chartjs is chartjs wrapper for Vue. It is JavaScript library you can use either CDN or NPM version. I going to use it with NPM, it is so easy.

npm install: npm install vue-chartjs chart.js --save

Create a doughnut

We can simply create a new component using TS /JS in your Vuejs app. Remember the component can’t have template section, since Vue don’t merge templates.

Following is a simple component which uses Mixin to combine props, Doughnut chart from vue-chartjs. The props also have default values, so that can leave the props blank for testing ( for example color).

import { Component, Mixins } from "vue-property-decorator"
import { Doughnut, mixins } from "vue-chartjs";
import Vue from "vue";

const chartProps = Vue.extend({
    props: {
        blockColors: {
            type: [],
            default: [
                "#ff6384",
                "#36a2eb",
                "#cc65fe"
            ]
        },
        data: {
            type: [] ,
            default: [140,50,60]

        },
        labels: {
            type: [],
            default: ["Red",  "Blue","Violet"],
        }
    }

});
@Component({
    extends: Doughnut, // this is important to add the functionality to your component
    mixins: [mixins.reactiveProp]
})
export default class ChjsDoughnutChart extends Mixins(mixins.reactiveProp, Doughnut,chartProps) {
    mounted() {
        // Overwriting base render method with actual data.
        this.renderChart({
            datasets: [
                {
                    backgroundColor: this.blockColors,
                    data: this.data,                    
                }
            ],
            labels: this.labels
        })
    }
}

Use the component

We can import and use the component in the template as follows

<template>
...
 <ChjsDoughnutChart :data="data" :labels="labels" :blockColor="blockColor"  />
...
</template
<script>
import ChjsDoughnutChart from "../charts/Doughnut";
@Component({
  components: { ChjsDoughnutChart },
})
.....
</script>

Here “data” and “labels” are the data members of the component

Following vue-chart post deserver a good read

Optional field in TS Interface

How to create optional member/field in typescript interface


Optional member in a TypeScript interface is the one that is not a mandatory field. We can skip those field while assigning values, everything else is mandatory.

To create a optional member we can use ? in front of the member and before the type.

..
firstName: string;
lastName?: string;
..

Following TypeScript posts may help your better understand TypeScript

How to Modules in Vuex

State management in Vuejs with Vuex module store Using Typescript. All you need to know for kick start Vuex store modules


So far We have been using props to pass data through parent child chain in our vuejs apps. This can be still working, we can do these data transactions and state management in a much easier way.

This is tutorial uses Typescript

Vuex Store Modules

Vuex store can be organized as modules, so that we can organize the data in a better way.Each module has its own state, mutations, actions and getters. Each state should have a type.

Products Module and interfaces

First up all create types for our state. The state is a indented to store values (array), so we have to define two types, one for state variable and another for array type.

</p>
export interface productState {
    products: Product[];
}

export interface Product {
    id: number;
    product: string;
    pk: string;
    mfr: string;
    hsn?: string;
    ts: number;
} 
<p>

We can store these types into a separate file which is recommended.

Vuex store ?

State management in Vuejs with Vuex store. All you need to know for kick start Vuex store


So far We have been using props to pass data through parent child chain in our vuejs apps. This can be still working, we can do these data transactions and state management in a much easier way.

What is a Vuex Store

Vuex store is state management module which helps developers to manage state of the object, and allow access data from any component through out the project.

How to add Vuex to Project

We can add Vuex to any project, by enabling the feature while creating new project or using Vue CLI as follows

vue add vuex

Components

Under the store reside under the store folder, usually in index file. A Vuex store can be made of modules or it can be standalone store with following sections

  • State – where data kept
  • mutations – which change state
  • Actions – methods which use state
  • Getters – which can access state

Chartjs for Vuejs

How to use Chartjs charts in Vuejs


When it come to chart I should mention Morris chart which I start developing my very first Python Flask app. It offer pretty nice charts. But for Vue I recommend you to use Chartjs.

Vue-Chartjs

Chartjs has Vue wrapper variant (opensource) which is based on Original Chartjs. It is JavaScript library you can use either CDN or NPM version. I going to use it with NPM, it is so easy.

npm install: npm install vue-chartjs chart.js --save

Example

Here is a simple TypeScript example ( provided by the official GitHub repository)

// CommitChart.ts
import { Component, Mixins } from 'vue-property-decorator'
import { Bar, mixins } from 'vue-chartjs';
import { Component } from 'vue-property-decorator';

@Component({
    extends: Bar, // this is important to add the functionality to your component
    mixins: [mixins.reactiveProp]
})
export default class CommitChart extends Mixins(mixins.reactiveProp, Bar) {
  mounted () {
    // Overwriting base render method with actual data.
    this.renderChart({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      datasets: [
        {
          label: 'GitHub Commits',
          backgroundColor: '#f87979',
          data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
        }
      ]
    })
  }
}

What Next ?

lol, create custom component for charting , so that you can use them in other projects.

One of the key point to remember that the chart component class doesn’t have a CSS and Template section. According to documentation it can’t have template section. So you have to use another component using the above component.

Following vue-chart post deserver a good read

TS class component in Vuejs

TypeScript vue component , you may miss the computed but there is getter and setters.


TypeScript is a modern typed language which is a superset of vanilla JavaScript. For easy development TS is a great tool . Let’s learn how to build a Vue component using TS.

JS and TS

One of the important difference between a JS component and TS component is that how the , data, computed and methods are organized.

Data

The data ( ) is replaced in TS class by regular variables, arrays etc.

Methods

As we know methods hold functions and event handlers, in TS class it is just functions.

Computed

Remember computed ? the reactive functions which automatically computed ? In TS class component it becomes get and set methods.

Here is a sample TS class component

<template>
  <div>{{ this.name }}</div>
</template>

<script>
const nameProp= Vue.extend({
  props: {
    name: {
      type: String,
    },
  },
});
export default class NewComponent extends nameProp {
  //data
  version : 1.0
  //method
  method1(){
  conole.log('some text')  
  }  
};
</script>

<style lang="scss" scoped></style>

The following vue posts may help you

How to add props in Vuejs component using TypeScript

How to define props in Vue TS component class


Props / properties area meant to display initial values on component and also meant to parent – child communication. So how to add a props Vuejs TS class component ?

Props in TS class

TypeScript allow us to separate Props from class, by extending and create a Prop object. I recommend this method.

  • Create props object by extending Vue class
  • Use the object to create our component class
</p>
<template>
  <div>{{ this.name }}</div>
</template>

<script>
const nameProp= Vue.extend({
  props: {
    name: {
      type: String,
    },
  },
});
export default class NewComponent extends nameProp {
  //data
  version : 1.0
  //method
  method1(){
  conole.log('some text')  
  }  
};
</script>

<style lang="scss" scoped></style>
<p>

Import

Lets import and use the component, place it in your template and specify the props value.

</p>
import New from "@/components/New.vue";

<template>
 <New name='Vue'/>
</template>
@Component({
  components: {    
    New
  },
})
...
<p>

The following vue posts may help you

How to add interface as props in Vuejs

How to define a interface and use as component props in Vuejs app


This is another TypeScript post for Vuejs users. We had seen how to add props in TS, if you miss those, use the following links

[display posts include_excerpt=true id=5278,5285]

Interface

Interface is like structure for Object. We can declare custom types in our project as Interfaces which can be organized in a file and folder (best practice).

Here is our sample Interface, this will hold value for Task

//types/index.ts
export interface Task{
    id: number,
    title: string,
    isdone: boolean
}

Defining props as custom type

Using props as Object Vue let us use Interface as Type. We can’t do it directly, instead Vue provide PropType. Let me show

import Vue, { PropType } from "vue";
import { Task } from "@/Types";

const editProp = Vue.extend({
  props: {
    task: {
      type: Object as PropType<Task>,
    },
  },
});
export default class EditDialog extends editProp {
...
}

Using the PropType we specify the Interface/Type and that should work.

The following vue posts may help you

How to capture data in Angular ReactiveForm using Form Builder

How to capture data from a Angular reactive form using formbuilder


Form submission is an essential part of any commercial application. So lets learn about capturing data in Reactive Form which is give emphasize to component side.

We can use advance form builder to create model, interact with form data, validation ect.

  • Import Form Builder
  • Add dependency injection in constructor
  • Create a group using Form Builder service
  • Create getters for easy access
  • Bind the fomGroup and FormControlName

app.module import

We have to add import ReactiveFormsModule to app.module.ts as follows

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
.....
 imports: [
    BrowserModule,
    ReactiveFormsModule,   
  ],

Form Builder in component.ts

Form Builder service allows to create formGroup with various property like validation. Also declared three getter functions to quickly access data. The code of our component class will look like

import {FormBuilder } from '@angular/forms';
... 
 constructor(private fb: FormBuilder) {}   
  get Item(): any {
    return this.todoForm.get("item");
  }
  get Desc(): any {
    return this.todoForm.get("description");
  }
todoForm = this.fb.group({
    item: ["formBuilder example", [Validators.required, Validators.minLength(4)]],
    description: ["", Validators.required],
  });

Binding the control

We can replace the name property of input with formControlName. So that the data in the FormGroup will be automatically updated. and the template will look like

{{todoForm | json}}
<form [formGroup]="todoForm"   novalidation (ngSubmit)="OnSubmit()"  >
      <div class="form-group">
      <label>Title</label>
 <input type="text" required  [class.is-invalid]="Item.invalid && Item.touched" class="form-control" formControlName="item">
      </div>
      <div class="form-group ">
      <label>Description</label>
      <textarea class="form-control" formControlName="description" ></textarea>
      </div>
       <button  type="submit" class="btn btn-primary">Submit</button>
      </form>

The interpolation statement will display the data.

When ever the user change the data the {{todoForm | json}} will output the value and it is live data.

Now you know how to capture data in a Reactive form using formBuilder

A set form projects available in the Source-Code Page

These angular post may help you

[display posts tag=angular-form]