This is mainly a question on how to add/extend any existing type with static
custom methods.
I want to have the String
prototype extended with a function, e.g. isNullOrEmpty
which should be invoked the C#
way:
if(!String.isNullOrEmpty(myStringToCheck)){
// do things as of myStringToCheck is set to something
}
In plain javascript I could do something like
String.isNullOrEmpty = function (s) {
if (s == null || s === "")
return true;
return false;
}
But, when calling it inside a TypeScript
it tells me
The property 'isNullOrEmpty' does not exist on value of type '{ prototype: String; fromCharCode(...codes: number[]): string; (value?: any): string; new(value?: any): String; }'.
How can this be done so it is known by TypeScript
?
Edit #1
How is String.fromCharCode()
implemented which is already known by TypeScript
?
Edit #2
Because of other dependencies in the project I'm currently only allowed to use TypeScript 1.0
!
Edit #3
String.d.ts
interface StringConstructor {
isNullOrEmpty(): boolean;
}
interface String {
format(...args: any[]): string;
isNullOrEmpty(): boolean;
}
and my String.ts
/// <reference path="../../../typings/String.d.ts"/>
String.prototype.format = function (): string {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp("\\{" + i + "\\}", "gi");
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
}
String.isNullOrEmpty = function(s) { <-- here is the exception
if (s == null || s === "")
return true;
return false;
}
Solution #1 (TypeScript
version > 1.0?)
see first answer by MartyIX
Solution #2 (workaround for TypeScript
version 1.0)
see second answer