# 🏅 Day 18 - 常見運算子 TypeScript 還是有許多實用的運算子,為了確保各位在攻略 TypeHero 上能夠更順利,這裡分享一些較常見的運算子 ## typeof 運算子 1. JavaScript:`typeof` 用途在於型別確認 2. TypeScript:`typeof` 則用於**取得型別** 以下我們來觀察 TypeScript 的 `typeof` 功能 ```tsx= let str = "Hello, TypeScript"; let num = 123; // 關鍵,使用 typeof 來取得型別 type StrType = typeof str; // string 型別 type NumType = typeof num; // number 型別 let anotherStr: StrType; // string 型別 let anotherNum: NumType; // number 型別 anotherStr = "Hello, World"; // 正確 anotherNum = 456; // 正確 // 下面的程式碼會產生錯誤,因為型別不匹配 // anotherStr = 789; // anotherNum = "TypeScript"; ``` ## keyof + typeof 組合技巧 我們在 day 14 有學到 [keyof](https://hackmd.io/B2oIhprASCmQoG5nG68mUA?view) 的概念,此時也可以拿來搭配使用 ```tsx= const fruit = { name: "Apple", color: "Red" } // 使用 keyof typeof 來取得 fruit 物件的屬性名稱型別 // 等同 type FruitLiteralType = "name" | "color" type FruitLiteralType = keyof typeof fruit let fruitPropertyLiteral: FruitLiteralType fruitPropertyLiteral = "name" // OK fruitPropertyLiteral = "color" // OK fruitPropertyLiteral = "taste" // Error: 不存在名稱為 "taste" 的屬性 ``` 這個範例中的步驟為: 1. 從原始物件中提取出**型別(typeof)**,也就是`{ name: string, color: string }` 2. 接著將型別 key 取出**聯合型別+字串字面量(keyof)**,並使用在新的 Type 上,也就是 `type FruitLiteralType = "name" | "color"` ### 在列舉(enum) 也能使用 keyof typeof ```tsx= enum Month { January = "JAN", February = "FEB", March = "MAR", // 其他月份... } type MonthKeys = keyof typeof Month; function printMonthAbbreviation(monthKey: MonthKeys) { console.log(Month[monthKey]); } printMonthAbbreviation("January"); // 輸出:JAN printMonthAbbreviation("Unknown"); // 錯誤:Type '"Unknown"' is not assignable to type '"January" | "February" | "March"'. ``` ## keyof typeof 結論 當你需要動態存取一個物件屬性時,就很適合使用 keyof typeof 來取得物件的 key ,藉此限制可以存取的屬性。 ## 其它常見運算子 1. in 2. `[]`:取出 key 對應的型別 3. infer 4. is ## 題目 透過 Hackmd、部落格形式,撰寫你不熟悉的 TypeScript 運算子,或是從未接觸過,但新版本的 TypeScript 有擴充實用的 [Utility Types](https://www.typescriptlang.org/docs/handbook/utility-types.html) 回報區 --- | Discord | CodePen / 答案 | Note | |:-------------:|:----------------------------------------------------------------:|:----------------------------------------------------------------:| |洧杰|[Codepen](https://codepen.io/hexschool/pen/poYgYqW?editors=1010)| |hannahpun|[部落格](https://medium.com/hannah-lin/typescript-%E7%94%A8%E7%94%9F%E6%B4%BB%E4%BE%8B%E5%AD%90%E5%9C%96%E8%A7%A3-utility-type-2eeee27a58cd)| 用生活例子圖解 Utility Type |HsienLu|[Blog](https://hsienlu.github.io/2024/01/31/TypeScript-%E5%B8%B8%E7%94%A8%E5%8A%9F%E8%83%BD-Readonly/)|| |claire chang|[Blog](https://clairechang.tw/2023/03/23/typescript/ts-utility-types/)||
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up