【发布时间】:2021-12-20 10:37:55
【问题描述】:
我为 String 创建了一个新接口,以使用 Monkey-patching 技术添加一些实用方法。
interface String {
toCamelCase(): string;
}
String.prototype.toCamelCase = function (): string {
return this.replace(/[^a-z ]/gi, '').replace(
/(?:^\w|[A-Z]|\b\w|\s+)/g,
(match: any, index: number) => {
return +match === 0
? ''
: match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
},
);
};
当我调用这个新函数时在我的控制器中: toCamelCase :
const str: string = 'this is an example';
const result = str.toCamelCase();
console.log(result);
我有这个错误:
[Nest] 35664 - 错误 [ExceptionsHandler] str.toCamelCase 不是函数 TypeError: str.toCamelCase 不是函数
这个实现有什么问题?
【问题讨论】:
-
我把第一个代码sn-p放在同一个文件.ts接口和String.prototype.toCamelCase = function()......我应该把它们放在单独的文件中
-
你的意思是它不起作用? It's absolutely working in this playground link 不过,我不建议猴子修补
-
@JayMcDoniel 为什么我在调用 str.toCamelCase(); 时会出现该错误来自我的控制器?
-
不知道你是如何包含猴子补丁的,这将是不可能的。
-
只需创建一个实用方法。
camelCaseString(str) => camelCasedString。现在您不必担心Strinig原型是否正确获取toCamelCase,并且它更容易测试(在我看来)
标签: javascript typescript nestjs typescript2.0 monkeypatching