I need to have some global prototype functions on the string class. Eg.
string.prototype.trimWhiteSpaces = function () {
return this.replace(/ +/g, \'\');
The problem is TypeScript doesnt know about these type definitions.
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.
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.