打字稿声明

时间:2021-04-01 20:54:43

标签: javascript typescript declaration

我目前正在学习 Typescript 声明,但我坚持将不同数量的参数传递给函数的概念。

换句话说,我如何为这样的 JavaScript 函数进行 Typescript 声明:

// Formats a string with the supplied parameter(s)
// Examples Usage: 
//  formatString("User {0} logged in", 'John');
//  formatString("Max {0} words allowed", 128.8999);
//  formatString("Form {0} to {1}", [10, 100]);

const function FormatString(sTemplate, params) {
    if (typeof params != undefined && arguments.length == 2) {
        if (params.constructor != Array) {
            if (typeof params == 'string')
                params = [params];
            else
                params = [String(params)];
        }

        if (params.constructor == Array) {
            $.each(params, function (index, value) {
                if (typeof value == 'string')
                    sTemplate = sTemplate.replace(new RegExp("\\{" + index + "\\}", "g"), value);
                else
                    sTemplate = sTemplate.replace(new RegExp("\\{" + index + "\\}", "g"), String(value));
            });
        }
    }
    return sTemplate;
}

1 个答案:

答案 0 :(得分:0)

一些提示:

  1. 在 JavaScript/TypeScript 中,当您想要表示严格相等或不相等时,不要使用 ==!=;相反,执行===!==,否则语言perfoms a looser comparison(例如4 == '4'true,而4 === '4'false) .
  2. 要检查某事物是否是 Array,更惯用的解决方案是 Array.isArray(obj)
  3. 尽量避免使用 arguments。它被认为是不好的做法并在实践中被弃用,有时根本无法访问。使用 rest 参数通常更好(更安全、更容易)使用。
  4. 要将 number 转换为 string,最好使用 .toString() 方法,它确保它实际上是一个正确的值和 errors when empty
  5. 不需要对 $ 之类的东西使用 each() 或任何花哨的依赖; array.forEach() 现在应该在浏览器中得到很好的支持。

综上所述,对您的代码进行意见重写将是:

const formatString = (sTemplate: string, ...params: Array<string | number>) => {
    params.forEach((value, index) => {
        const newValue = typeof value === 'string' ? value : value.toString(10);
        sTemplate = sTemplate.replace(new RegExp("\\{" + index + "\\}", "g"), newValue);
    });
    return sTemplate;
};

formatString("User {0} logged in", 'John');
formatString("Max {0} words allowed", 128.8999);
formatString("Form {0} to {1}", 10, 100);

注意允许额外的 params,而不是数组。虽然您可以实现您在消息中的内容(单个参数或参数数组),但我认为这有点不习惯,可能会引起混淆。

在我上面的例子中,你可以仍然通过使用像这样展开的数组来传递一个数组作为参数(如果它是在其他地方生成的):

const nums = [10, 100];
formatString("Form {0} to {1}", ...nums);

如果你想保留你原来的语法,你可以这样使用:

const formatString = (sTemplate: string, params?: Array<string | number> | string | number) => {
    if (params !== undefined) {
        const newParams = Array.isArray(params) ? params : [params];
        newParams.forEach((value, index) => {
            const newValue = typeof value === 'string' ? value : value.toString(10);
            sTemplate = sTemplate.replace(new RegExp("\\{" + index + "\\}", "g"), newValue);
        });
    }
    return sTemplate;
};

formatString("User {0} logged in", 'John');
formatString("Max {0} words allowed", 128.8999);
formatString("Form {0} to {1}", [10, 100]);
formatString("No params");

但另外一个警告是,如果 undefined 是单个参数,则不能将其用作实际参数;它会假设它不存在并且不会在模板中执行替换。

祝你学习之旅好运! JavaScript 是一种存在一些问题的语言,例如上面提到的 ==/!= 情况,但 TypeScript 确实可以更轻松地获得有效、安全的代码,因此我建议继续沿用这条路!