Typescript extension method compiling but not working at run time

天涯浪子 提交于 2021-01-28 21:52:52

问题


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?

来源:https://stackoverflow.com/questions/37438151/typescript-extension-method-compiling-but-not-working-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!