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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With