[TypeScript] Types 十全大補下— Mapped Types

Mapped type loops over all of the possible keys, and determines the appropriate value type for each key

Hannah Lin
Hannah Lin

--

TypeScript 系列文

1. The Very Basics for TS
2. Generics 的使用情境
3. The `extends` keyword
4
. GenericsMapped Types

5. 用生活例子圖解 Utility Types
6
. 優雅的在 React 中使用 TS
7. 用 ts-migrate 仙女棒讓 JS 專案瞬間 migrate 成 TS

雖然研究進階 TS 過程真的很容易進入昏睡狀態 (一直在看 document 跟線上課程),但看到 Mapped Types 這個單元還是讓我眼睛一亮瞬間驚醒,Mapped Types 著重處理 object,而 object 又是實務上最常用的 type,因為真的很實用,所以決定寫一篇筆記文。

我知道 medium 實在不太適合寫技術文,但我都花 N 個小時做圖了,希望把這無聊的東西筆記的有趣些 。

🔖 文章索引1. Buzz Word for mapped type
2.
From basics
3.
Index signature: use key
4. Mapped Types: loops over all of the possible keys
5. Built-in utility type
6. Template literal types: Easy to transform the keys and values

Buzz Word for mapped type

先來名詞解釋一下比較有概念

object type

顧名思義就是處理 object 的型別 (好像廢話),interface 也只能定義 object type

// object type
interface IUser {
name: string;
age: number;
}

// object type
type TUser = {
name: string;
age: number;
}

// Primitive Data Types
type name = string;

--

--