What I want is to extend the String prototype to add a .trimSlashes() method to wipe slashes from either end of a string; I can't make it do in-place replacement (instead of requiring to return a string, just change the own string on call), but that'd be another issue.
I am using TypeScript version 3.8.3.
So I have this trimSlashes.ts file:
import * as fs from "fs";
interface String {
trimSlashes(this: string) : string;
}
String.prototype.trimSlashes = function (this : string) : string {
var str = this;
if (str.startsWith("/")) {
str = str.replace(/^\/+/, "")
}
if (str.endsWith("/")) {
str = str.replace(/\/+$/, "");
}
return str;
}
let test = "//myTest/";
console.log("Original string: " + test);
test.trimSlashes();
console.log("Trimmed slashes: " + test);
console.log("File or directory exists: " + fs.existsSync(test));
I added the fs context as it was required to trigger the error where the compiler stops the parse complaining that Property 'trimSlashes' does not exist on type 'String'.. Without the fs code, it builds and run over NodeJS.
Additional notes
There are several questions like this but seems none asks it for version 3.8 and all answers I could find did not apply.
I tried creating a separate .d.ts file, including it in source, and now I'm trying what I believe to be the simplest: declaring all in one file. I wouldn't mind having a .d.ts file if required, but I just can't get it to work.