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
- Angular2在本地开发中慢速自动刷新页面 – Windows
- 如何在用Typescript和ES6编写的NodeJS中运行黄瓜testing
- 使用mongoose的打字稿错误
- 如何让TypeScript编译器不发出目录结构
- 在调用AppComponent.ts之前,Angular 2的起点是什么?
- 错误TS7027:在Angular2 TypeScript Service类中检测到无法访问的代码
- 从客户端传递给nodeJS时,string转换为Object
- Typescript模块导入configuration文件
- 在打字稿中访问Nodejsstream的highWaterMark属性给出:“Property'_readableState'不存在”错误