Typescript Tips and tricks for JS Developers (Part2)

Introduction 🚩:

Hallo 🇩🇪🇹🇳 :

Dear Followers and Readers, I'm so glad today to present for you my second part about Typescript Tips and tricks, I got positive feedback about the first part that didn't cover all the available tips and the rich skins provided by Typescript, so I decided to add a second part to talk about :

  • Custom decorators
  • Deeper with Generics (Constraints)

I hope it will be a helpful bog ✍️ dear community, Happy reading :)

#Tip1: Custom decorator 🔧 🔨

We will start with a very interesting and useful feature provided by Typescript is: “Custom Decorators” 🛡🛡 .

Decorators are a way to add annotation 🚧 and meta-programming syntax to classes and their properties or parameters for some scenarios,

For example in Angular this a list of use cases that we can use Decorators :

  • Tracking component property changes through ngOnchanges.
  • Calling unsubscribe to avoid memory leaks.
  • Complicated calculations outside the Angular area.
  • Calculate execution time
  • Processing and logging errors.
  • Using Storage API.
  • Page Params

etc …

Problem ⛔️:

While developing some features in your project you will deal with routine actions, repeated tasks, and duplication of code 🚩! which will cause a bad smell as the project grows!

Solution ✅ :

With typescript, we can benefit from the custom decorator feature

I will show you an example of how to implement a custom decorator (Safe)

So we will implement an annotation ‘Safe’ that will be added to avoid unexpected errors while dealing with Storage API

Code explanation ✂️:

  • SafeDecoratorParams: define the params type that can be passed to our decorator
  • SafeDecoratorLogLevel: Enum type that represents the available Logging levels
  • export function Safe<T>: defining the name of our decorator
  • const originalMethod = descriptor.value: we first cache the original method implementation
  • const logLevel = params.logLevel || SafeDecoratorLogLevel.Default: get the current Logging level
  • descriptor.value = function (…args) {: Our custom logic (for our case when there is an error caught we will choose to make a console message or your custom error handler and return our descriptor(decorator)
  • StorageService implementation :

Now we will add our decorator to the methods implemented in our storage-service

  • App.component.ts :

Now we will inject our service inside the app component and make just a call for an unexisting item in localStorage: “test”, and check the two scenarios (without “@Safe”, with “@Safe” )

import { Component } from '@angular/core';import { StorageService } from './services/storage.service';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss'],})export class AppComponent {title = 'customDecoratorwith';constructor(private storageService: StorageService) {}ngOnInit() {console.log(StorageService.getItem('test'));}}
  • Result without Decorator safe ✖️ :
  • Result with Decorator safe ✔️ :

#Tip2: More deep with Generics (constraint)🔧 🔨:

Now I will try to explain something interesting about Typescript Generics not mentioned in the previous blog: “Generic constraint” ⛏.

So as we said TypeScript generics help us to write reusable code, but there are some things we should consider to work with Generics 🚩:

  1. Will this function or class be required to work with a variety of data types
  2. Will this function or class be used in more than one place ❔

In addition, we can apply a constraint to Generic type parameters by using the “keyword extends” for more type checking and to ensure type properties exist.

Code-Example 📙 ✍️:

We are implementing a Generic function getLength(args: T) that will return the length of args passed as params!

Problem ⛔️: But if the args doesn't have a length property! 🚫 🚫

(an error will be thrown )

Solution ✅:

Defining an interface functtArgs for type checking and by adding

<T extends functArgs>

We are telling our compiler that will accept only args having the length property!

References 📓 📕:

Conclusion ✍️:

In conclusion, In part 2 of Typescript tips, I just tried to cover and explain interesting features like Custom Decorators and Generic Constraints that can be helpful and useful for JS developers while writing code on server-side or client-side. ⛹ ⛏

Waiting for your feedback :)

You can follow me :



Thanks 🙏




<script>alert('try your best')</script>

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Reproducible builds for I2P

Redux at Cobalt.io

Five Minute C# — Lesson 9

Here Are 7 Useful Node Packages (Open Source and Free to Use!)

Create a Modal with React, Typescript and portals!

How I Made a Multiplayer Snake Game 🐍

How I Made a Multiplayer Snake Game 🐍

Test-Driven Development in 5 steps

An Introduction to the bind() Method in JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rebai Ahmed

Rebai Ahmed

<script>alert('try your best')</script>

More from Medium

Sharing Code Between Web and Hybrid Mobile Applications (Part 1) — Ionic and Angular

Angular Framework

Ionic 5 Auth Guard Implementation

Business Benefits & Types of Applications to Build with Angular Frontend Framework