What you will accomplish
After reading this post you will be able to extend the Javascript Object Prototype of String to use a custom function directly on strings.
Instead of writing:
let text = 'some text';
text.charAt(0).toUpperCase() + text.slice(1); // 'Some text'
You will write:
let text = 'some text';
text.capitalize(); // 'Some text'
What is the Object Prototype?
The Javascript Object Prototype is a mechanism used for object inheritance. In short, each object has a hidden reference to another object called its prototype.
Extending a prototype adds new features that become available to all objects of the same type.
How to extend the Object Prototype
Using Typescript, declare a global String interface and specify the wanted function.
declare global {
interface String {
capitalize(): string;
}
}
Afterwards add the actual implementation to the Object Prototype.
String.prototype.capitalize = function (): string {
return this.charAt(0).toUpperCase() + this.slice(1);
};
Applying a function grants you access to the current string using this context instead of passing the text as a parameter.
Usage
Now you are able to use the new utilty function on every string variable in your code.
let text = 'some text';
text.capitalize(); // 'Some text'
or directly on a string
'some text'.capitalize(); // 'Some text'
Summary
Is it cool? Hell yeah! And by far the most minimal approach.
Is it best practice? Noooot really.
Upsides
- extremly elegant on primitive data types
- clean and minimal
- no additional parameters needed -> this context used
- chaining is possible
Downsides
- new EcmaScript standards might introduce functions with same naming
- might collide with 3rd party libraries
- developers need to be aware of it