TypeScript 特殊型別
TypeScript 具有可能不指向任何特定資料型別的特殊型別。
型別:any
any
是一個停用型別檢查並允許使用所有型別的型別。
下面的示例未使用 any
,並且會引發錯誤
不使用 any
的示例
let u = true;
u = "string"; // Error: Type 'string' is not assignable to type 'boolean'.
Math.round(u); // Error: Argument of type 'boolean' is not assignable to parameter of type 'number'.
自己動手試一試 »
將 any
設定為特殊型別 any
會停用型別檢查
使用 any
的示例
let v: any = true;
v = "string"; // no error as it can be "any" type
Math.round(v); // no error as it can be "any" type
自己動手試一試 »
any
可以是繞過錯誤的一種有用方式,因為它停用了型別檢查,但 TypeScript 將無法提供型別安全性,並且依賴於型別資料的工具(如自動完成)將無法工作。記住,應“不惜一切代價”避免使用它……
型別:unknown
unknown
是 any
的一個相似但更安全的選擇。
TypeScript 會阻止使用 unknown
型別,如下面的示例所示
let w: unknown = 1;
w = "string"; // no error
w = {
runANonExistentMethod: () => {
console.log("I think therefore I am");
}
} as { runANonExistentMethod: () => void}
// 當我們不知道型別時,如何避免註釋掉的程式碼中的錯誤?
// w.runANonExistentMethod(); // Error: Object is of type 'unknown'.
if(typeof w === 'object' && w !== null) {
(w as { runANonExistentMethod: Function }).runANonExistentMethod();
}
// 儘管我們必須多次進行型別斷言,但我們可以透過 if 語句進行檢查以確保我們的型別安全並進行更安全的型別斷言
自己動手試一試 »
將上面的示例與前面的 any
示例進行比較。
unknown
最適合用於你不知道資料型別的時。要稍後新增型別,你需要進行型別斷言。
型別斷言是當我們使用 "as" 關鍵字來說明屬性或變數是已斷言型別時。
型別:never
never
在定義時實際上會引發錯誤。
let x: never = true; // Error: Type 'boolean' is not assignable to type 'never'.
自己動手試一試 »
never
很少使用,尤其是單獨使用時,它的主要用途是在高階泛型中。
型別:undefined & null
undefined
和 null
是分別指向 JavaScript 原語 undefined
和 null
的型別。
let y: undefined = undefined;
let z: null = null;
自己動手試一試 »
除非在 tsconfig.json
檔案中啟用了 strictNullChecks
,否則這些型別的用途不大。