Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 Add an extension method to primitives

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.

like image 940
Ori Refael Avatar asked Jan 01 '23 15:01

Ori Refael


1 Answers

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'  
like image 119
Sachila Ranawaka Avatar answered Jan 06 '23 03:01

Sachila Ranawaka