在 TypeScript 3.8 中扩展字符串

Extend String in TypeScript 3.8

我想要的是扩展 String 原型以添加一个 .trimSlashes() 方法来从字符串的两端擦除斜杠;我无法让它进行就地替换(而不是要求 return 一个字符串,只需在调用时更改自己的字符串),但那是另一个问题。

我使用的是 TypeScript 版本 3.8.3。

所以我有这个 trimSlashes.ts 文件:

import * as fs from "fs";

interface String {
  trimSlashes(this: string) : string;
}

String.prototype.trimSlashes = function (this : string) : string {
  var str = this;
  if (str.startsWith("/")) {
    str = str.replace(/^\/+/, "")
  }
  if (str.endsWith("/")) {
    str = str.replace(/\/+$/, "");
  }

  return str;
}

let test = "//myTest/";

console.log("Original string: " + test);
test.trimSlashes();

console.log("Trimmed slashes: " + test);

console.log("File or directory exists: " + fs.existsSync(test));

我添加了 fs 上下文,因为需要它来触发编译器停止解析并抱怨 Property 'trimSlashes' does not exist on type 'String'. 的错误。如果没有 fs 代码,它会在 NodeJS 上构建和 运行。

补充说明

有几个类似的问题,但似乎 none 要求它用于 3.8 版,我能找到的所有答案都不适用。

我尝试创建一个单独的 .d.ts 文件,将其包含在源代码中,现在我正在尝试我认为最简单的方法:在一个文件中声明所有内容。如果需要,我不介意有一个 .d.ts 文件,但我就是无法让它工作。

我认为添加 import * as fs from 'fs' 会强制编译器将该文件视为一个模块。当这种情况发生时,Typescript 会意识到在一个更大的程序中有一个全局范围可能会受到这个文件的影响,并且不会让全局原型变得混乱,除非你告诉它你真的有意这样做。

要显式修改全局接口,请使用 declare global

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

Playground

我会把它放在我项目根目录的 string.d.ts 中。 Typescript 应该选择它并允许该方法。请务必在任何可能使用它的代码之前导入将此函数添加到实际原型的文件,否则您仍然会遇到运行时错误。