Typescript Tips and tricks for JS Developers (Part2)

Introduction 🚩:

Hallo 🇩🇪🇹🇳 :

  • Deeper with Generics (Constraints)

#Tip1: Custom decorator 🔧 🔨

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

  • Calling unsubscribe to avoid memory leaks.
  • Complicated calculations outside the Angular area.
  • Calculate execution time
  • Processing and logging errors.
  • Using Storage API.
  • Page Params
  • 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 :
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'));}}

#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” ⛏.

  1. Will this function or class be used in more than one place ❔
<T extends functArgs>

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. ⛹ ⛏

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