寫法
Pick<Type, Keys>
由一個 Type 所擁有的屬性中,選取幾個屬性建構出一個新的 type。
舉個例子
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | type IDMapping = {STUDENT: {
 school: string;
 name: string;
 grade: string;
 },
 ENGINEER: {
 company: string;
 position: string;
 salary: string
 }
 }
 
 type CHILD: Pick<IDMapping, 'STUDENT'>;
 
 const person: CHILD = {
 STUDENT: {
 school: 'abc university',
 name: 'John',
 grade: 'freshman',
 }
 }
 
 console.log(person.STUDENT.school);
 
 | 
上面的例子,可以看到我們製作出一張總列表 IDMapping,裡面包含所有,我們之後會用到的型別的定義。
假設今天我們想要做出一個學生身分的型別,我們就可以利用 Pick 只抓出 IDMapping 裡面有關學生的
類別定義的部分。
專案實際作用
Pick 這個方法真的蠻好用的。
在專案中,我們可能有好幾種含有不同 head 項目的 table,所以,我們就可以將專案中會用到的 table 的
head 的項目,定義在一張總 type 裡面。
等到某一種 table 需要使用總 type 裡的某一種 table 的類別的時候,就可以利用 Pick 把他抓出來定義。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 
 | type tableMapping = {USER_LIST: {
 staffId: string;
 firstName: string;
 lastName: string;
 mail: string;
 }
 USER_HISTORY: {
 updatedTimestamp: string;
 editor: string;
 role: string
 }
 TRANSACTION_LIST: {
 dealTimestamp: string;
 price: string
 transaction_way: string
 }
 }
 
 type user_info: Pick<tableMapping, 'USER_LIST'|'USER_HISTORY'>
 const staff: user_info = {
 USER_LIST: {
 staffId: '1254';
 firstName: 'Jay';
 lastName: 'Lin';
 mail: 'xxx@hotmail.com';
 },
 USER_HISTORY: {
 updatedTimestamp: '1680016023';
 editor: 'Jay Lin';
 role: 'manager'
 }
 }
 
 console.log(staff.USER_LIST.staffId, staff.USER_HISTORY.editor);
 
 | 
以上範例的寫法,就可以讓專案的某一個區域裡,同時擁有 USER_LIST 和 USER_HISTORY 這兩個類別合在一起的資料囉。
Reference
- https://www.typescriptlang.org/docs/handbook/utility-types.html