I would like to extend the String prototype and use it in one or more components of my Angular 5 application. The main reason is that I have a series of objects, which have properties that sometimes are populated, and sometimes not. Example: customer.address
is sometimes a string
(the _id
of the address) and sometimes it's populated and it's an Address
object, with an _id
property.
What I want is basically not have to worry whether customer.address is populated or not, and simply access the _id
. I know it's considered a Javascript anti-pattern according to some other responses here, but I thought of doing something like this:
String.prototype._id = function () {
return String.prototype.valueOf()
}
Regardless of how bad of an idea this is -already answered in other questions-, would this be a way of doing it, and where should I declare this? Is there a better way of solving this issue?
Thanks.
PS. I know I could also overwrite the toString
method in my Address
class and get a similar result, calling customer.address.toString()
to get the _id
, but I feel like it's not legible and I'd like to explore other options first.