[英]Extending String.prototype in JavaScript
I've started to make my string-related function as extension methods in JavaScript, 我已经开始将与字符串相关的功能作为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. 我的问题是,当我添加如下所示的扩展方法时,该方法有效,但未在VS Code的Intellisense中显示。
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. 例如,如果我在.js文件中定义扩展名,然后导入该文件,则期望看到类似“ test” .format的方法,但看不到该方法。
Create a file index.d.ts
that contains the type declaration of your function : 创建一个文件
index.d.ts
,其中包含函数的类型声明:
interface String {
format(): string;
}
For more information see JavaScript Language Service in Visual Studio 有关更多信息,请参见Visual Studio中的JavaScript语言服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.