0

在 TypeScript中扩展String字符串原型prototype

 2 years ago
source link: https://www.myfreax.com/zai-typescript-3-8-zhong-kuo-zhan-zi-fu-chuan/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
更新于 2021/07/31 |  创建于 2021/07/31

在 TypeScript中扩展String字符串原型prototype

在Typescript中如果你在javascript原型prototype中添加方法,Typescript是不会检测到的,当这种情况发生时,你需要显式的告知Typescript,只有才不会让全局原型prototype出现混乱。

要显式修改全局接口,请使用declare global ,下面的示例中修改String原型prototype,并在String原型prototype中添加capitalize方法

declare global {
  interface String {
    capitalize(this: string): string;
  }
}

String.prototype.capitalize = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK