iT邦幫忙

2024 iThome 鐵人賽

DAY 15
0
JavaScript

TypeScript 初學者也能看的學習指南系列 第 15

TypeScript 初學者也能看的學習指南 15 - any 任意型別

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20240925/20149362TEVc7zCV4p.png
any 是 TypeScript 獨有的型別,它的功用如同它的名字,任何型別都可以接受
當一個變數被定義為 any 時,就是在告訴 TypeScript 編譯器說:「請繞過這邊不要做型別檢查」,跟 @ts-ignore 有異曲同工之妙呢!

本篇將來介紹 any 該注意的地方以及使用時機 gogo~

❌ Don't

Don’t use any as a type unless you are in the process of migrating a JavaScript project to TypeScript.
in cases where you don’t know what type you want to accept, or when you want to accept anything because you will be blindly passing it through without interacting with it, you can use unknown.

擷取自官方文件

會開門見上放上「Don't」,是因為這段挺重要的,官方建議要盡量避免使用 any
因為 any 會 disables 所有型別的檢查,這樣就失去了 TypeScript 型別檢查的意義了。當我們在不確定要接受什麼型別的情況下,或不想限制接受的型別是哪些時,使用 unknown 替代 any 會是更好的選擇

那既然這樣,為什麼 TS 還要創造 any 型別呢?
下面來說說它的使用時機

✅ Do's

1. 搬遷專案、過渡時期
當你正在把 JavaScript 轉換為 TypeScript 時,就很適合使用 any 。避免在搬遷過程中,頻繁跳出型別檢查錯誤

2. 無法確定外部資料的格式
這裡的外部資料指的像是外部 API 取得的 JSON,當用 JSON.parse('...') 來解析時,因為不確定 JSON 的格式是什麼,所以解析出來的結果也是不確定的,這時就很適合使用 any

3. 第三方套件
有些第三方套件並不是用 TypeScript 去寫,在這種情況下,使用 any 可以幫助開發者在使用第三方套件時不會因為型別問題而報錯,拉長開發進度

範例

  1. 當宣告一個變數,但沒有賦值,就會被編譯際自動推論為 any
let a; // let a: any
  1. 任何型別都可以賦值給 any; any 也可以賦值給任何型別
// ✅ 以下都是 Pass
let anyValue: any;
anyValue = 0;
anyValue = true;
anyValue = 'hello';
anyValue = [1, 2, 3];
anyValue = { x: 1, y: 2 };
anyValue = function () { };
anyValue = () => { };
anyValue = class { };
anyValue = new Date();
anyValue = null;
anyValue = undefined;
anyValue = Symbol('hello');

let str: string = anyValue;
let num: number = anyValue;
let bool: boolean = anyValue;
let obj: object = anyValue;
  1. any 甚至還可以訪問不存在的屬性和方法,如此自由的操作會讓程式碼處在一個很不安全的情況下
// ✅ 以下都是 Pass
let obj2: any = { x: 0 } // 拿掉 any  就會報錯了
obj2.foo();
obj2();
obj2.bar = 100;
obj2 = "hello";
const n: number = obj2;

我也看到官方說了一句很直白有趣的話:「當你用 any 時,你應該要比 TypeScript 更了解環境」😆
在 Type Assertion 裡也是這麼說的

you know the environment better than TypeScript.

tsconfig.json 中的 noImplicitAny

Enable error reporting for expressions and declarations with an implied 'any' type.

當你沒有指定型別且 TypeScript 無法從上下文中推斷型別時,通常會預設為 any
要避免這樣的情況,就把 tsconfig.json 中的 noImplicitAny 設為 true,它會強制要所有無法進行型別推論的變數、參數和屬性都要明確指定型別,換句話說,就是不允許 any 的存在~

{
  "compilerOptions": {
    "noImplicitAny": true,
    // 其他配置選項
  }
}

noImplicitAny 設置為 true,下面這段就會報錯

// Parameter 's' implicitly has an 'any' type.
function fn(s) {
  console.log(s.foo());
}

每天的內容有推到 github 上喔

References


上一篇
TypeScript 初學者也能看的學習指南 14 - Type Assertion 型別斷言
下一篇
TypeScript 初學者也能看的學習指南 16 - unknown 未知型別
系列文
TypeScript 初學者也能看的學習指南16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言