You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为String原型添加自定义toCamelCase方法后TypeScript报TS2339错误的问题咨询

String原型添加自定义toCamelCase方法后TypeScript报TS2339错误的问题咨询

大家好,我最近在给String.prototype添加一个自定义的toCamelCase方法时遇到了TypeScript类型错误,折腾了半天没解决,想请教下各位大佬。

具体报错信息如下:

error TS2339: Property 'toCamelCase' does not exist on type 'string'.

console.log('**** ', element.toCamelCase())

下面是我的代码实现:

global.d.ts 文件内容

declare global {
  interface String {
    toCamelCase(): string
  }
}

export {}

converter.ts 文件内容

interface String {
  toCamelCase(): string
}

String.prototype.toCamelCase = function () {
  return this.toLowerCase()
    .replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
      return index === 0 ? word.toLowerCase() : word.toUpperCase();
    })
    .replace(/\s+/g, '');
}

我已经尝试过把converter.ts里的String接口定义注释掉,但完全没有效果,错误还是原样出现。有没有朋友知道问题出在哪里,该怎么解决呢?

备注:内容来源于stack exchange,提问作者jkalandarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 12:04:28