有時,您會獲得有關 TypeScript 不知道的值類型的資訊。
例如,如果你使用 document.getElementById,TypeScript 隻知道這會傳回某種 HTMLElement,但你可能知道你的頁面總是有一個帶有給定 ID 的 HTMLCanvasElement。
在這種情況下,您可以使用類型斷言來指定更具體的類型:
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
與類型注釋一樣,類型斷言由編譯器删除,不會影響代碼的運作時行為。
您還可以使用尖括号文法(除非代碼在 .tsx 檔案中),它是等效的:
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
TypeScript 隻允許類型斷言轉換為更具體或不太具體的類型版本。 此規則可防止“不可能”的強制,例如:
const x = “hello” as number;
Conversion of type ‘string’ to type ‘number’ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘unknown’ first.
Sometimes this rule can be too conservative and will disallow more complex coercions that might be valid. If this happens, you can use two assertions, first to any (or unknown, which we’ll introduce later), then to the desired type.
如下圖所示:
