【问题标题】:Typescript monkey patching doesn't work for String打字稿猴子修补不适用于字符串
【发布时间】: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


【解决方案1】:

与其污染String 原型,我建议创建一个函数camelCase(str: string): string,该函数接受您想要驼峰式大小写的字符串并在驼峰化后返回它。类似的东西

export const camelCase = (str: string): string => {
  return str.replace(/[^a-z ]/gi, '').replace(
    /(?:^\w|[A-Z]|\b\w|\s+)/g,
    (match: any, index: number) => {
      return +match === 0
        ? ''
        : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
      },
    );
}

现在它可以像import { camelCase } from './utilties'; 一样导入并像camelCase('Hello World!'); 一样调用

与尝试修改 String 原型相比,这将导致该函数更独立、更健壮且更易于测试,此外,原型修改不再常见。

【讨论】:

    猜你喜欢
    • 2012-10-13
    • 2019-03-29
    • 2021-10-30
    • 1970-01-01
    • 2023-03-31
    • 2020-08-09
    • 2016-10-30
    • 1970-01-01
    • 2012-03-13
    相关资源
    最近更新 更多