3

I have extended the String prototype in Typescript with a simple method:

StringExtensions.ts

String.prototype.toCleanedTitleCase = function ():string {
    let titleCase = this.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
    })
    return titleCase.replace(new RegExp(" ", 'g'), "").replace(new RegExp("-", 'g'), "")
}

Then added an interface in a definition file:

StringExtensions.d.ts

interface String {
    toCleanedTitleCase():String;
}

Then calling it:

index.ts

console.log(("Some string that needs a-sorting").toCleanedTitleCase();

All compiles fine, but when I run my app (node js), I get "xxx.toCleanedTitleCase" is not a function.

Any ideas what I'm missing?

Paul Grimshaw
  • 19,894
  • 6
  • 40
  • 59
  • That was just an example, get the same error on normal strings – Paul Grimshaw May 25 '16 at 13:16
  • Have you inspected the compiled js to make sure the function is indeed there? My guess is that you are neither setup for AMD nor compiling to a single output file and therefore the StringExtensions content isn't making it into the output. It will still compile if you have a /// to the file. – Andrew May 25 '16 at 13:24
  • 1
    That's exactly it. Adding require("./StringExtensions) to the top of my index fixed it – Paul Grimshaw May 25 '16 at 13:38
  • Where did you put this require("./StringExtensions)? To the top of your index? Where is this? your index.ts? If I put a similar line like this in my index.ts, it does not even compile at compile time. – Ravior Feb 15 '19 at 10:20
  • ` "paths": { "@extensions/*": [ "src/extensions/*.extensions.ts" ] } ` and `import '@extensions/array';` in file where extension method used works for me – smg May 22 '19 at 11:24

0 Answers0