Adding a custom method to a string in TypeScript can be achieved like so:
const myPoint : string = "23";
const customNumber = myPoint.convertUsingMyCustomImplementation();
Attempting to define the method with a capital 'S' results in the following errors:
// eslint-disable-next-line no-extend-native
String.prototype.convertUsingMyCustomImplementation = function() : number {
return parseFloat(this);
};
However, there are two errors that occur:
https://i.sstatic.net/LiZZ0.png
Property 'convertUsingMyCustomImplementation' does not exist on type 'String'.
Argument of type 'String' is not assignable to parameter of type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
Another attempt with the following code:
// eslint-disable-next-line no-extend-native
string.prototype.convertUsingMyCustomImplementation = function() : number {
return parseFloat(this);
};
Also results in an error:
https://i.sstatic.net/4zbDt.png
To address these errors and successfully add a custom method in TypeScript, the correct approach should be considered.