What is the best way to write utilities in TypeScript?

  angular, architecture, ecmascript-6, javascript, service

I am trying to build some common utility methods (or functions) in order use through different components. However, there are many different ways and before using one of them, I want to get idea what is the differences and most suitable one for some situations. Here are the different ways below, but if you suggest a different way please let me know:

method I: Quite normal functions (grouped in a file)

export function sum(a: number, b: number): number {
    return a + b;
}

and call it from a component via import:

import * as <mynamespace> from <somepath>

method II: using service

export class ExampleService {

   public sharedVariable: any;

   public sharedFunction() {
       // your implementation
   }
}


export class Component1 {
    public constructor(private service: ExampleService) {
        this.service.sharedFunction();
        this.service.sharedVariable;
    }
}

export class Component2 {
    public constructor(private service: ExampleService) {
        this.service.sharedFunction();
        this.service.sharedVariable;
    }
}

method III: using abstract class

export abstract class BaseClass {

   public sharedVariable: any;

   public sharedFunction() {
       // your implementation
   }
}


export class Component1 extends BaseClass {
    public constructor() {
        super();
        this.sharedFunction();
        this.sharedVariable;
    }
}

export class Component2 extends BaseClass {
    public constructor() {
        super();
        this.sharedFunction();
        this.sharedVariable;
    }
}

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.