How To Solve The Error “Property ‘ReplaceAll’ Does Not Exist On Type ‘String'”?

Property ‘replaceAll’ does not exist on type ‘string’

The error “Property ‘replaceAll’ does not exist on type ‘string'” occurs infrequently. It relates to versions. What is the cause of it? And how to solve it? Let’s go into detail now.

The reason for the error “Property ‘replaceAll’ does not exist on type ‘string'”

The error “Property ‘replaceAll’ does not exist on type ‘string'” happens when you are running an old Typescript version or ECMAScript that does not support the replaceAll string method.

The replaceAll method was just recently provided in ES2021. You can read more here.

Example of how the error happens:

const aString: string = "Hello From Learn Share IT.";
const replacedString: string = aString.replaceAll(" ", "");
console.log(replacedString);

Error:

Property 'replaceAll' does not exist on type 'string'.

The solutions for this error

Setting tsconfig.json

Example:

{
    "compilerOptions": {
        // Some code line
        "lib": [
            // Some other code line
            "ES2021.String"
        ]
    }
}

Then now, we can use the replaceAll method.

Example:

const aString: string = "Hello From Learn Share IT.";
const replacedString: string = aString.replaceAll(" ", "");
console.log(replacedString);

Output:

HelloFromLearnShareIT

Install the latest Typescript version

If your error is not solved, make sure you are running a new version. You can check your Typescript version by this command:

tsc –v

You can download the recent Typescript version by this command:

npm install –g typescript@latest

or

npm install –save-dev typescript@latest

Use replace() method

We can make the replace() method apply the effect in all strings by combining with the RegExp object. There are a lot of ways to use RegExp object, but RegExp provides a very useful literal notation which is / /g. With it, we can replace all occurrences with replace() method.

Example:

const aString: string = "Hello From Learn Share IT.";
const replacedString: string = aString.replace(/ /g, "");
console.log(replacedString);

Output:

HelloFromLearnShareIT

Or you can replace the string like this:

const aString: string = "Hello Hello From Learn Share IT";
const replacedString: string = aString.replace(/Hello/g, "Welcome");
console.log(replacedString);

Output:

Welcome Welcome From Learn Share IT

Here, with a string, you do not have to wrap it inside the quotation mark.

Summary

In this tutorial, I have shown you how to solve the error “Property ‘replaceAll’ does not exist on type ‘string'”. You should set your tsconfig.json file with "ES2021.String" or can use replace() method with RegExp object instead of the relaceAll() method. Let’s try them to get your desired results!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *