Alex
Alex

Reputation: 1046

Extending String.prototype in JavaScript

I've started to make my string-related function as extension methods in JavaScript,

My issue is when I add an extension method like below, the method works but it doesn't show up in the Intellisense of VS Code.

String.prototype.format = function() {
    let str = this.toString()
    if (arguments.length) {
        const type = typeof arguments[0]
        const args = type === 'string' || type === 'number' ? Array.prototype.slice.call(arguments) : arguments[0]

        for (const arg in args) str = str.replace(new RegExp(`\\{${arg}\\}`, 'gi'), args[arg])
    }
    return str
}

As an example, if I define the extension in a .js file and then import the file, I'm expecting to see the method like "test".format but I don't see the method.

Upvotes: 1

Views: 1431

Answers (1)

Mohamed Ramrami
Mohamed Ramrami

Reputation: 12691

Create a file index.d.ts that contains the type declaration of your function :

interface String {
    format(): string;
}

For more information see JavaScript Language Service in Visual Studio

Upvotes: 4

Related Questions