Search code examples
typescriptprototypewebstorm

Typescript string prototype show error in webstorm IDE


I defined the following format function to String. This works OK, but the problem is that webstorm is marking the "String.prototype.format" in red. How can I suppress the error?

interface String {
    format(variables:Array<string>):string
}

String.prototype.format = (variables:Array<string>):string => {
    return this.replace(/%(\d+)/g, function(_,m) {
        return variables[--m];
    });
};

Thanks


Solution

  • I found a workaround for this, I ended up with this:

    interface String {
        format(variables:Array<string>):string
    }
    
    if (!String.hasOwnProperty("format")) {
        String.prototype["format"] = function (variables:Array<string>) : string   {
            return this.replace(/%(\d+)/g, function(_,m) {
                return variables[--m];
            });
        };
    }