4.5 Declaring legacy external modules

We could arguably avoid mentioning legacy external modules in this book because we should try to avoid using them but it is possible that we will encounter some code samples on the internet or old type definitions files that are still using them. It is important that we cover them so we can migrate them into the new recommended module declaration syntax for external modules: ES6.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher.

How to do it

The library included in the companion source code declares a library called ndrscr. This library is implemented using legacy external modules under the following directory:

/chapter_03/src/module_definitions/design_time/external/external

Let’s take a look to the arrays.ts file:

import { IArrays } from '../../interfaces';

class Arrays implements IArrays {
  public first<T>(array: Array<T>, n = 1): Array<T> {
    const result = [];
    for (let i = 0; i < n; i++) {
      const value = array[i];
      if (typeof value === 'undefined') {
        return result;
      }
      result.push(array[i]);
    }
    return result;
  }

  public last<T>(array: Array<T>, n = 1): Array<T> {
    return this.first(array.reverse(), n);
  }
}

export default new Arrays();

How it works

It is important to understand that external legacy modules are used at design time. The arrays module declares a class names Arrays. This class has two methods. The first one is named first and it can be used to get the first n elements of an array:

first([5, 4, 3, 2, 1], 3); // [5,4,3]

The second method is named last and it can be used to get the last n elements of an array:

last([5, 4, 3, 2, 1], 3); // [1,2,3]

Then an instance of the class Arrays is created and, finally, it is exported using the export keyword.

Source Code

Declaring legacy external modules

See also

Please refer to the next recipe (Importing legacy external modules) to learn how you can consume legacy external modules.


Shiv Kushwaha

Author/Programmer