簡體   English   中英

Typescript 聲明

[英]Typescript declaration

我目前正在學習 Typescript 聲明,但我堅持將不同數量的參數傳遞給 function 的概念。

換句話說,我如何為 JavaScript function 做一個 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. 在 JavaScript/TypeScript 中,當你想要表示嚴格相等或不相等時,不要使用==!= 相反,請執行===!== ,否則該語言會進行更寬松的比較(例如4 == '4'true ,而4 === '4'false )。
  2. 要檢查某物是否是Array ,更慣用的解決方案是Array.isArray(obj)
  3. 盡量避免使用arguments 它被認為是不好的做法,在實踐中已被棄用,有時根本無法訪問。 使用rest參數通常更好(更安全、更容易)使用。
  4. 要將number轉換為string ,最好使用.toString()方法,它可以確保它實際上是一個正確的值,並且在為空時會出錯
  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 確實更容易獲得有效、安全的代碼,所以我建議留在這條路上!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM