「キャスティング」は変換とは異なります。この場合、window.location.hashは数値を文字列に自動変換します。ただし、TypeScriptコンパイルエラーを回避するために、文字列変換を自分で行うことができます。
window.location.hash = ""+page_number;
window.location.hash = String(page_number);
これらの変換は、page_numberis nullまたはのときにエラーがスローされないようにする場合に最適ですundefined。一方page_number.toString()、またはのpage_number.toLocaleString()場合page_numberはスローされます。nullundefined
変換ではなくキャストのみが必要な場合、これはTypeScriptで文字列にキャストする方法です。
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
<string>またはas stringキャスト注釈は御馳走に活字体のコンパイラに伝えるpage_number、コンパイル時に文字列として。実行時に変換されません。
ただし、コンパイラは文字列に数値を割り当てることができないと不平を言うでしょう。最初ににキャストし<any>、次ににキャストする必要があります<string>。
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
したがって、実行時とコンパイル時に型を処理するだけで変換が簡単になります。
window.location.hash = String(page_number);
(文字列番号のキャストの問題を発見してくれた@RuslanPolutsyganに感謝します。)
page_numberあるnullこれが設定されますwindow.location.hash文字列*に"null"。(私はエラーを好む:D)。