In .net/c#, you can define an extension method like this:
public static bool IsBlank(this string s)
{
return String.IsNullOrEmpty(s);
}
and call it like this:
string myString = null
if(myString.IsBlank()) ...
This is extremely useful for dealing with strings that may be null.
In Typescript and javascript, I would very much like to do the same thing, something like this:
String.prototype.isBlank = function ()
{
return this === null || this === undefined || this == '';
}
var myString: string = null
if(myString.isBlank()) ...
but it doesn't work, because javascript doesn't know anything about the fact that myString
is typed as string
, or was in the Typescript file, anyway. So you get an error like 'isBlank' is not a member of null
.
The only real workaround is something klunky like if((mystring || '').isNotBlank())
, but that gets tedious (and error prone).
In javascript, is there any way to extend null itself so that a call like null.coerce(defaultValue)
would work?
If not, is there a way to cause typescript to transpile null.coerce(defaultValue)
into (null || defaultValue)
?
Update:
I know I could always write coerce(variable, defaultValue)
, but I think that's an even more klunky syntax.
Update 2: My simple code snippet was too simple to illustrate the use case, as vanilla javascript has simple workarounds, as some answers said.
In a real application, suppose I get a complex table object back from some API call, and I want to write something like:
var x = result.rows[i].field[j].parseAsInt(0).toString()
because rows(i, j) is some legacy field that's an integer, but they stored it as a string so they could use "-" instead of null or zero, but sometimes they DO use null, and I have to deal with it by mapping any such thing to zero. My parseAsInt
method would be something that says "if it's parseable as an integer, return the integer, otherwise ("-", null, undefined) the specified default value. The alternative would be
var x = (result.rows[i].field[j] || 0).parseAsInt(0).toString()
and that is a more awkward syntax.