TypeScript Type Assertions - 类型断言
有時,您會獲得有關 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.
如下圖所示:
總結
以上是生活随笔為你收集整理的TypeScript Type Assertions - 类型断言的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数字在计算机中的表示
- 下一篇: 生产无人机的股票有哪些