2

I'm trying to compile my ts code with the target ES2020 as my node version is v14.17.3, according to the following tsconfig:

{
    "compilerOptions": {
      "target": "es2020",
      "lib": ["ESNext.String"],
      "module": "commonjs",
      "allowJs": true,
      "outDir": "./build",
      "esModuleInterop": true
    }
}

As String.prototype.replaceAll is not supported in node v14.17.3 I'm getting error when running the code below, probably because the compiler is not replacing replaceAll with a valid expression in the target ES2020:

const text = "my text"
const newText = text.replaceAll(' ', '-')
console.log(newText)
TypeError: text.replaceAll is not a function

Shouldn't Typescript compiler convert text.replaceAll(' ', '-') to a valid expression in the target ES2020?

Jeff Pal
  • 1,519
  • 1
  • 17
  • 28
  • `text.replaceAll(' ', '-')` is a syntactically valid expression in ES2020 so there's nothing to convert it to. If you're asking why TypeScript doesn't *polyfill* `String.prototype.replaceAll()`, it's because [they don't do that](https://stackoverflow.com/questions/56276280/why-is-es7-array-polyfill-needed-despite-the-tsconfig-target-is-set-to-es5). – jcalz Sep 25 '21 at 03:23
  • The "lib" field (https://www.typescriptlang.org/tsconfig#lib) means "assume these features are supported in the environment where the generated JavaScript will run". It doesn't mean that polyfills will be provided. – user2740650 Sep 25 '21 at 03:25
  • @jcalz I think it's supported in ES2021, not ES2020. At least I had to target ES2021 to avoid an error in https://www.typescriptlang.org/play. – user2740650 Sep 25 '21 at 03:28
  • I'm saying that `text.replaceAll(' ', '-')` is a *valid expression* in every version of JavaScript that I know of. So is `foo.bar(123)` and `text.scoobydoobles(' ', '-')`. For all of those, the TypeScript compiler will emit that code to JavaScript as-is. There's nothing to "convert". On the other hand, `foo.bar(...baz)` is an invalid expression in ES5 but valid above that, and such an expression might be converted to something else depending on compiler settings. – jcalz Sep 25 '21 at 03:36

0 Answers0