Top 3 Useful TypeScript Tips for Angular

Top 3 Useful TypeScript Tips for Angular

Top 3 Useful TypeScript Tips for Angular

These are the 3 tips I found pretty handy while working with Typescript:

  1. Eliminating the need to import interfaces
  2. Making all interface properties optional
  3. Stop throwing me error, I know what I'm doing

Though I discovered these while working with Angular application, but all tips are not Angular specific, it's just Typescript.

Eliminating the need to import interfaces

I like interfaces. However, I don’t like to import them everytime. Although Visual Studio Code has auto-import feature, I don’t like my source files been “polluted” by multiple lines of imports - just for the purpose of strong typing.

Table of Contents
  1. Eliminating the need to import interfaces
  2. Making all interface properties optional
  3. Stop throwing me error, I know what I'm doing

This is how we do it normally.

// api.model.ts
export interface Customer {
    id: number;
    name: string;
}

export interface User {
    id: number;
    isActive: boolean;
}
// using the interfaces
import { Customer, User } from './api.model'; // this line will grow longer if there's more interfaces used

export class MyComponent {
    cust: Customer; 
}

Solution 1: Using namespace

By using namespace, we can eliminate the needs to import interfaces files.

// api.model.ts
namespace ApiModel {
    export interface Customer {
        id: number;
        name: string;
    }

    export interface User {
        id: number;
        isActive: boolean;
    }
}
// using the interfaces
export class MyComponent {
    cust: ApiModel.Customer; 
}

Nice right? Using namespace also help you to better organize & group the interfaces. Please note that you can split the namespace across many files.

Let's say you have another file called api.v2.model.ts. You add in new interfaces, but you want to use the same namespace.

// api.v2.model.ts
namespace ApiModel {
    export interface Order {
        id: number;
        total: number;
    }
}

You can definitely do so. To use the newly created interface, just use them like the previous example.

// using the interfaces with same namespaces but different files
export class MyComponent {
    cust: ApiModel.Customer; 
    order: ApiModel.Order;
}

Here is the detail documentation on Typescript namespacing.

Solution 2: Using d file

The other way to eliminate import is to create a typescirpt file end with .d.ts. “d” stands for declaration file in Typescript (more explanation here).

// api.model.d.ts
// you don't need to export the interface in d file
interface Customer {
    id: number;
    name: string;
}

Use it as normal without the need to import it.

// using the interfaces of d file
export class MyComponent {
    cust: Customer; 
}

I recommend solution 1 over solution 2 because:

  • d file usually use for external, 3rd party declaration
  • namespace allow us to better organize the files
Making all interface properties optional

It's quite common where you will use same interface for CRUD. Let's say you have a customer interface, during creation, all fields are mandatory, but during update, all fields are optional. Do you need to create two interfaces to handle this scenario?

Here is the interface

// api.model.ts
export interface Customer {
    id: number;
    name: string;
    age: number;
}

Solution: Use Partial

Partial is a type to make properties an object optional. The declaration is included in the default d file lib.es5.d.ts.

// lib.es5.d.ts
type Partial<T> = {
    [P in keyof T]?: T[P];
};

How can we use that? Look at the code below:

// using the interface but make all fields optional
import { Customer } from &apos;./api.model&apos;;

export class MyComponent {
    cust: Partial<Customer>;  /

    ngOninit() {
        this.cust = { name: &apos;jane&apos; }; // no error throw because all fields are optional
    }
}

If you don't find Partial declaration, you may create a d file yourself (e.g. util.d.ts) and copy the code above into it.

For more advance type usage of Typescript, you can read here.

Stop throwing me error, I know what I’m doing

As a Javascript turns Typescript developer, one might find Typescript error is annoying sometimes. In some scenario, you just want to tell Typescript, “hey, I know what I am doing, please leave me alone.”.

Solution: Use @ts-ignore comment

From Typescript version 2.6 onwards, you can do so by using comment @ts-ignore to suppress error.

For example, Typescript will throw error “Unreachable code detected” in this following code:

if (false) {
    console.log(&apos;x&apos;);
}

You can suppress that by using comment @ts-ignore

if (false) {
    // @ts-ignore
    console.log(&apos;x&apos;);
}

Find out more details here: Typescript 2.6 release

Of course, I will suggest you to always try fix the error before ignoring it!

Summary

Typescript is good for your (code) health. It has pretty decent documentation. I like the fact that they have comprehensive What&apos;s new documentation for every release. It’s an open source project in Github if you would like to contribute. The longer I work with Typescript, the more I love it and appreciate it.

That's it, happy coding!

Source viva: https://scotch.io/tutorials/3-useful-typescript-tips-for-angular

Learn More

How to master advanced TypeScript patterns

Angular Authentication Tutorial

Build a CRUD App with Angular and Firebase

Integrating Google Analytics With Angular 2+

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

The Web Developer Bootcamp

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

Angular JS Development Company

If you’re finding AngularJS Development Company for consultation or Development, your search ends here at Data EximIT 

🔗 Click here to know more: AngularJS Development




Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.