Angular CLI - How to share prototype functions across the application

The problem is TypeScript doesnt know about these type definitions.


Quick Method

Provide definitions for each of the methods you're using

Open typings.d.ts and add the following:

interface String {
  trimWhiteSpaces: () => string;
}

You will have to provide definitions for each function you're consuming. While this is faster, it may be a good time to reevaluate prototypes.js and make it TypeScript friendly.


Pro Method

Convert the Library to typescript and import/export functions as needed. This is more time consuming, but if you own the library it's something you're going to want to do eventually.

If you wanted to update the library and still use the prototype (which doesnt treeshake well) you would do something like this:

File: string-prototypes.ts

String.prototype.trimWhiteSpaces = trimWhiteSpaces;

interface String {
  trimWhiteSpaces: typeof trimWhiteSpaces;
}

function trimWhiteSpaces() {
  return this.split(' ').join('');
}

At the top of your app.module.ts import this file like so:

import './string-prototypes';

The second approach would be to structure your library like this, and import the functions as needed.

File: string-helpers.ts

export function trimWhiteSpaces(input: string) {
  return input.split(' ').join('');
}

In a component:

import { trimWhiteSpaces } from './string-helpers';

You loose the prototype augmentation this way, but it guarantees consumers of your library are only using what they need.


You can simply declare such interface as global in a separate file and export it so that typescript knows about it.

So your file e.g. prototypes.ts should look like this:

export {}; // Using the export, there is no need to import the file anywhere.

declare global {
    interface String {
        trimWhiteSpaces(): string;
    }

    interface Array<T> {
        isEmpty(): boolean;
        isNotEmpty(): boolean;
    }
}

if (!String.prototype.trimWhiteSpaces)
    String.prototype.trimWhiteSpaces = function (): string {
        return this.replace(/ +/g, '');
    }
}

if (!Array.prototype.isEmpty) {
    Array.prototype.isEmpty = function <T>(): boolean {
        return this?.length === 0;
    };
}

if (!Array.prototype.isNotEmpty) {
    Array.prototype.isNotEmpty = function <T>(): boolean {
        return this?.length > 0;
    };
}