Monkey 將函式修補到現有類中

有時能夠使用新函式擴充套件類是有用的。例如,假設應該將字串轉換為駝峰大小寫字串。所以我們需要告訴 TypeScript,String 包含一個名為 toCamelCase 的函式,它返回一個 string

interface String {
    toCamelCase(): string;
}

現在我們可以將此功能修補到 String 實現中。

String.prototype.toCamelCase = function() : string {
    return this.replace(/[^a-z ]/ig, '')
        .replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match: any, index: number) => {
            return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
        });
}

如果載入了 String 的這個擴充套件,它可以像這樣使用:

"This is an example".toCamelCase();    // => "thisIsAnExample"