--- tags: TypeScript 新手指南 --- # #3 新手指南:函式的型別 > 討論日期: 2021/11/16 > 討論範圍: 新手指南:函式的型別 ## 筆記分享 - https://dazedbear.notion.site/3-a076e5224fd5433a8ac26e8181117c37 ## 待解決問題 ## 線上討論紀錄 ### 學習資源推薦 [TypeScript type challenges](https://github.com/type-challenges/type-challenges/tree/master/questions) > 難度較高,建議看完基礎、進階比較熟了之後再來做練習比較好 [Udemy 線上課程:React and Typescript: Build a Portfolio Project](https://www.udemy.com/course/react-and-typescript-build-a-portfolio-project/learn/lecture/24186294?start=0) > 可以等看完這本新手指南後來看 ### 陳述式 vs 表達式 https://ithelp.ithome.com.tw/articles/10218937 ### Arguments 寫法比較 - PHP 也有類似的寫法 ```typescript= /** * 剩餘引數: 用陣列蒐集剩下的傳入參數 */ function push(array: any[], ...items: any[]) { items.forEach(function(item) { array.push(item); }); } // compare to arguments // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments#description function push(array: any[]) { const args: IArguments = arguments; let items: any[] = Array.prototype.slice.call(arguments, 1); items.forEach(function(item) { array.push(item); }); } ``` ### Overload - https://www.notion.so/dazedbear/3-a076e5224fd5433a8ac26e8181117c37#ca47a1f2b8ef4e0bbd5abdee98b9929c - PHP 沒有 Overload - 比較常見的情境 - 如加法也是一種overload的實踐,如果輸入兩數字相加,得到的結果是數字加總結果;輸入字串相加則得到兩字串連接在一起的結果。 - 有時候設計function會希望可以支援查詢單一或多個結果可能會寫成 ```typescript= interface User { id: number; name: string; } interface UserArray { [index: number]: User; } let userDataList: UserArray = [ { "id" : 1, "name" : "Tim" }, { "id" : 2, "name" : "Alice" } ]; function getUserData(id: number): string; function getUserData(id: Array<number>): Array<string>; function getUserData(id: number | Array<number>): string | Array<string> { if(typeof id === 'number'){ for (const x in userDataList) { if (userDataList[x].id == id){ return userDataList[x].name; } } } else if (typeof id === 'object') { let result = []; for (const x in userDataList) { for (const y in id) { if (userDataList[x].id == id[y]){ result.push(userDataList[x].name); } } } return result; } return ''; } const d1 = getUserData(2); //Alice const d2 = getUserData([1,2]); // [Tim,Alice] ```