关于javascript:将JS sprintf转换为等效的Typescript

Convert JS sprintf to Typescript equivalent

在寻找Javascript的\\'sprintf \\'函数时,我发现这个小函数既简单又符合我的要求:

1
2
3
4
5
6
7
function sprintf(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    var i = 0;
    return format.replace(/%s/g, function() {
        return args[i++];
    });
}

(原始来源:https://gist.github.com/rmariuzzo/8761698)

问题是我想在用Typescript编写的Angular 4应用程序中使用此函数,所以我无法调用它,因为编译器抱怨参数数量与该函数所需的参数不匹配。

我知道有Typescript等效项(f.i. https://github.com/alexei/sprintf.js),但需要使用npm安装模块,并且比我需要的复杂得多。

我从未在Typescript中使用过多个参数函数(除了在可选参数上使用\\'?\\'),所以我不知道如何使此函数适合在Angular应用中使用。

有什么想法吗?谢谢!


您可以使用rest参数:

1
2
3
4
5
6
function sprintf(format, ...args) {
    var i = 0;
    return format.replace(/%s/g, function() {
        return args[i++];
    });
}