Angular CLI - How to use prototype functions in an application

I need to have some global prototype functions in a string class. For instance.

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

I use the Angular CLI, and I want this feature to be available for all lines in my Angular 4 application. I added a piece of code to the file with the name prototypes.js, and to the .angular-cli.jsonfile loaded

  "scripts": [
      "assets/js/prototypes.js",
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/bootstrap/dist/js/bootstrap.min.js",
      "../node_modules/moment/min/moment.min.js"
    ],

However, I keep getting the following error while compiling my project

The `trimWhiteSpaces' property does not exist in the 'string' type.

How to make such features available throughout the application

+7
source share
2 answers

The TypeScript problem is not aware of these type definitions.


Quick method

,

typings.d.ts :

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

, . , , prototypes.js TypeScript .


Pro-

TypeScript / . , , , .

- ( ), - :

: string-prototypes.ts

String.prototype.trimWhiteSpaces = trimWhiteSpaces;

interface String {
  trimWhiteSpaces: typeof trimWhiteSpaces;
}

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

app.module.ts :

import './string-prototypes';

, , , .

: string-helpers.ts

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

:

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

-, , , .

+12

, ,

Angular

  2

  1. ,

-

Angular Docs ,

  1. - ( , )

, ,

, Angular

0

Source: https://habr.com/ru/post/1688558/


All Articles