Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript extend String Static

Tags:

typescript

Is there a way to add a isNullOrEmpty(str:string) to the static string object.

such that I can call it:

String.isNullOrEmpty(myobj);

I have found a way to put it on the implementation but that does not help for a method such as this.

like image 404
maxfridbe Avatar asked Jul 24 '13 19:07

maxfridbe


1 Answers

String is defined in lib.d.ts with the following interface

interface StringConstructor {
  ...
}

declare var String: StringConstructor;

so while you can't add methods to a variable, you can add them to the interface, using

interface StringConstructor {
   isNullOrEmpty(str:string):boolean;
}

and them implement them on the variable, using

String.isNullOrEmpty = (str:string) => !str;
like image 180
SWeko Avatar answered Sep 22 '22 18:09

SWeko