4

I would like to add few methods to primitives. I have the following file:

string-extension.ts:

interface String {
    isNullOrEmpty(this: string): boolean;
}

String.prototype.isNullOrEmpty = function (this: string): boolean {
    return !this;
};

I have a component which has the following code:

constructor () {
    let a = "asd";
    alert(a.isNullOrEmpty());
}

no import is added at the top. When I run the client, it crashes on that line.

a.isNullOrEmpty is not a function

When I inspect the code, i see that my string-extension.ts file wasn't included there. I am very familiar with the concept in C# but im not quite familiar with it in TypeScript, so if you need more info, ill provide.

Thanks.

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Ori Refael
  • 2,888
  • 3
  • 37
  • 68

1 Answers1

11

first, create global .d.ts. file to set up the signature.

global.d.ts.

export {}; // this file needs to be a module
declare global {
  interface String {
        isNullOrEmpty(this: string): boolean;
  }
}

string-extension.ts:

export {}; // this file needs to be a module
String.prototype.isNullOrEmpty = function (this: string): boolean {
    return !this;
};

Now in the main.ts import the extension

 import './string-extension'  
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • 1
    src/global.d.ts(1,9): error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations. – Ori Refael Nov 08 '18 at 12:07
  • yeah. saw that too in someone's answer and it worked. thanks alot – Ori Refael Nov 08 '18 at 12:16
  • 2
    I also think, it might be smart to mention where the `global.d.ts` file should be placed. If I am not mistaken, this should be in the root of the Angular project, right? – Fluous Aug 18 '19 at 07:07