string原型在浏览器中工作,但不在节​​点中

节点: 8.1.0

我有以下原型:

String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, '') } 

当我使用它时,像这样:

 // Mongoose Database Model: let project = new ProjectModel project.slug = title.toSlug() 

它似乎不能正常工作。 它所做的只是删除第一个空间,并添加一个破折号,如下所示:

 // Original: "Bed Time Stories" // Outputs: "BedTime-Stories" // Expected: "bed-time-stories" 

正如你所看到的,它甚至没有将string转换为小写字母。

然而,当我在jsfiddletesting这个,它创build正确的输出string。 这是什么原因造成的?

 interface String { toSlug(): string; } String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, '') } var str = "Bed Time Stories"; console.log(str.toSlug()); 

我发现这个错误,该接口提供了TypeScript的契约,允许新方法的可见性。 JavaScript实现提供了调用方法时将要执行的代码。 代码中缺less这个

来源: 在TypeScript中扩展function