YC
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 2024 TS 直播班每日任務 ## [🏅 Day 15 - TypeHero 大挑戰](https://hackmd.io/dEuFJ5IKQ4aOlygyPpf0Tw) ### [Primitive Data Types](https://typehero.dev/challenge/primitive-data-types) ```typescript= interface Musician { artistName: string; age:number; deceased: boolean; } const artistName:Musician['artistName'] = 'Frank Zappa'; const age:Musician['age'] = 52; const playSong = (artistName:Musician['artistName'], year:number):string => { return `${artistName} was released in the year ${year}`; }; const musicianInfo = (infoObj:Musician):string => { return `${infoObj.artistName}, age ${infoObj.age}${infoObj.deceased ? ' (deceased)' : ''}`; }; musicianInfo({ artistName, age, deceased: true, }); ``` ### []() --- ## [🏅 Day 14 - keyof](https://hackmd.io/B2oIhprASCmQoG5nG68mUA) ### 處理課程與學生資料邏輯 以下題目,**請嘗試用你認知的泛型技巧來進行優化,目前程式碼問題如下:** 1. **型別安全性降低**:沒有用介面或型別別名來定義物件資料結構,直接操作物件和其屬性,沒辦法享受型別檢查的好處,那幹嘛用 TypeScript 😂? 2. **程式碼重複性高**:都對多個物件進行相同的操作(例如取出某個屬性的值),都要為每個物件都寫一遍相同的程式碼,會導致程式碼的重複性高 🤮 3. **可讀性、可維護性差也不好**:觀看各個程式碼邏輯,感覺都是各寫各的操作物件和其屬性,要花更多心力去個別維護 🤧 4. **變得容易出錯**:綜合以上三點,在初期因為偷懶沒定義好資料結構(interface、type、泛型),以致於更容易在修改程式碼時出錯,而懷疑人生 🥺 ```typescript= interface Student { name: string; age: number; major: string; } // 建立一個學生物件 const student: Student = { name: '小明', age: 20, major: '資訊工程' }; function getStudentValue<T, K extends keyof T>(obj:T, key:K):T[K]{ return obj[key] } const studentName = getStudentValue(student, 'name'); const studentAge = getStudentValue(student, 'age'); const studentMajor = getStudentValue(student, 'major'); console.log(`學生姓名: ${studentName}`); console.log(`學生年齡: ${studentAge}`); console.log(`學生主修: ${studentMajor}`); // 建立一個課程物件 interface Course { title: string, credits: number, isRequired: boolean } const course:Course = { title: '程式設計', credits: 3, isRequired: true }; function getCourseValue<T, K extends keyof T>(obj:T,key:K){ return obj[key] } const courseTitle = getCourseValue(course,'title'); const courseCredits = getCourseValue(course, 'credits'); const courseIsRequired = getCourseValue(course, "isRequired"); console.log(`課程名稱: ${courseTitle}`); console.log(`學分數: ${courseCredits}`); console.log(`是否為必修: ${courseIsRequired ? '是' : '否'}`); ``` --- ## [🏅 Day 13 - type 泛型](https://hackmd.io/n72dWAA7RBqx9pkXfodQsA) ### 題目一: 資料庫重構優化 請嘗試將 `UserEntry` 和 `ProductEntry`重構,合併成一個自訂的 `type`,並使用泛型來進行優化 ```typescript= // 定義 UserEntry 和 ProductEntry 型別 type Entry<T> = { id:string; data:T } type UserEntry = Entry<{ name: string; age: number; }> type ProductEntry = Entry<{ name: string; price: number; }> // 建立 UserEntry 和 ProductEntry 的函式 function createUserEntry(id: string, data: { name: string; age: number; }): UserEntry { return { id, data }; } function createProductEntry(id: string, data: { name: string; price: number; }): ProductEntry { return { id, data }; } // 使用函式來建立 UserEntry 和 ProductEntry const userEntry = createUserEntry("user1", { name: "John Doe", age: 30 }); const productEntry = createProductEntry("product1", { name: "Apple iPhone 13", price: 799 }); ``` ### 題目二:旅館訂房網 請嘗試將 `RoomOperationResult` 和 `CustomerOperationResult`重構,合併成一個自訂的`type` ,並使用泛型來進行優化 ```typescript= // 定義 Room 型別別名 type Room = { id: string; type: string; price: number; available: boolean; } // 定義 Customer 型別別名 type Customer = { id: string; name: string; } // 定義 RoomOperationResult 和 CustomerOperationResult型別別名 type operationResult<T> = { success: boolean; data: T; message: string; } // 建立一個 Customer 陣列來儲存客戶資訊 let customers: Customer[] = []; // 定義一個函式,該函式接收一個 Room 並回傳一個 RoomOperationResult function bookRoom(room: Room): operationResult<Room> { // 檢查房間是否可用 if (room.available) { // 預訂房間,將 available 屬性設為 false room.available = false; const result: operationResult<Room> = { success: true, data: room, message: '預訂成功' }; return result; } else { const result: operationResult<Room> = { success: false, data: room, message: '房間已被預訂' }; return result; } } // 定義一個函式,該函式接收一個 Room 並回傳一個 RoomOperationResult function cancelRoom(room: Room): operationResult<Room> { // 取消房間,將 available 屬性設為 true room.available = true; const result: operationResult<Room> = { success: true, data: room, message: '取消預訂成功' }; return result; } // 定義一個函式,該函式接收一個 Customer 並回傳一個 operationResult<Customer> function addCustomer(customer: Customer): operationResult<Customer> { // 將客戶添加到客戶陣列中 customers.push(customer); const result: operationResult<Customer> = { success: true, data: customer, message: '新增客戶成功' }; return result; } // 建立一個 Room const room: Room = { id: '1', type: '單人房', price: 1000, available: true }; // 使用 bookRoom 函式來預訂房間 const bookResult = bookRoom(room); console.log(bookResult); // 輸出:{ success: true, data: { id: '1', type: '單人房', price: 1000, available: false }, message: '預訂成功' } // 使用 cancelRoom 函式來取消房間 const cancelResult = cancelRoom(room); console.log(cancelResult); // 輸出:{ success: true, data: { id: '1', type: '單人房', price: 1000, available: true }, message: '取消預訂成功' } // 建立一個 Customer const customer: Customer = { id: '1', name: 'John Doe' }; // 使用 addCustomer 函式來添加客戶 const addCustomerResult = addCustomer(customer); console.log(addCustomerResult); // 輸出:{ success: true, data: { id: '1', name: 'John Doe' }, message: '新增客戶成功' } console.log(customers); // 輸出:[{ id: '1', name: 'John Doe' }] ``` --- ## [🏅 Day 12- 泛型約束 extends](https://hackmd.io/Mx3Ok-bhRZ2wAe0NQbZTlA) ### **題目一:計算陣列總和** 開發一個函式 **`calculateSum`**,並接受一個數字陣列作為參數,來計算出其總和。請使用泛型約束來確保傳入的參數必須是數字陣列。 ```typescript= // 請改寫為泛型函式,並使用泛型約束 function calculateSum<T extends number>(array:T[]):number{ return array.reduce((a,c)=>a+c,0) ; } // 正常使用 const total = calculateSum([1, 2, 3, 4]); // 回傳 10 // 錯誤使用(會編譯錯誤,因為參數不是數字陣列) // const errorTotal = calculateSum(["a", "b", "c"]); ``` ### **題目二: 篩選擁有特定屬性的物件陣列** 開發一個函式 **`filterItems`**,該函式接受一個物件陣列,並回傳所有具有特定屬性的物件。使用泛型約束來確保每個物件至少包含該屬性。 ```typescript= interface WithName { name: string; } // 請調整為泛型函式,並使用 WithName 做為泛型約束條件,確保每個物件至少包含該屬性。 function filterItems<T extends WithName>(items:T[]):T[]{ return items.filter(item => item.name.startsWith("特定條件")); } // 正常使用 const filteredItems = filterItems([{ name: '特定條件物件1' }, { name: '其他物件' }]); // 錯誤使用(將導致編譯錯誤,因為陣列中的物件沒有 name 屬性) // const errorFilteredItems = filterItems([{ id: 1 }, { id: 2 }]); ``` ### **題目三: 泛型介面中的多屬性檢查** 開發一個函式 **`processData`**,該函式接受一個具有 **`id`** 和 **`data`** 屬性的物件。使用泛型約束來確保傳入的物件符合此結構。 ```typescript= interface DataItem { id: string; data: any; } // 請改寫為泛型函式,並使用泛型約束 function processData<T extends DataItem>(item:T) :void { console.log(`處理資料,ID 為: ${item.id}, Data: ${item.data}`); // ... 其他邏輯 } // 正常使用 processData({ id: '123', data: '任何資料' }); // 錯誤使用(將導致編譯錯誤,因為物件不符合 DataItem 結構) // processData({ id: '123' }); ``` ### **題目四: 事件處理器** 開發一個函式 **`handleEvent`**,該函式接受一個事件名稱和一個處理函式。使用泛型約束來確保事件名稱是特定集合的一部分。 ```typescript= type EventName = "click" | "mouseover"; // 請改寫為泛型函式,並使用泛型約束 function handleEvent<T extends EventName,U>(eventName:T, handler:U) { // ... 註冊事件處理函式邏輯,這裡僅示意不用寫 } // 正常使用 handleEvent("click", () => console.log("Clicked!")); // 錯誤使用(將導致編譯錯誤,因為 'scroll' 不是 EventName 的一部分) // handleEvent("scroll", () => console.log("Scrolled!")); ``` ### **題目五: 泛型約束用於資料處理的函式** 開發一個函式 **`processData`**,該函式接受一個包含 **`data`** 和 **`timestamp`** 屬性的物件。使用泛型約束來確保物件包含這些屬性。 ```typescript= interface DataWithTimestamp { data: any; timestamp: Date; } // 請改寫為泛型函式,並使用泛型約束 function processData<T extends DataWithTimestamp>(item:T) { console.log(`資料: ${item.data}, 時間戳: ${item.timestamp}`); } // 正常使用 processData({ data: "some data", timestamp: new Date() }); // 錯誤使用(將導致編譯錯誤,因為缺少 timestamp 屬性) // processData({ data: "some data" }); ``` --- ## [🏅 Day 11 - 什麼是泛型?](https://hackmd.io/uQqMVMDwSFysariS9KUAug) ### 題目一:建立泛型字串陣列 **函式名稱** `createGenericStringArray` **輸入** 兩個字串 `str1` 和 `str2`。 **輸出** 一個泛型陣列 `Array<string>`,包含 `str1` 和 `str2`。 **範例** 輸入`"hello"` 和 `"world"`,函式回傳陣列為 `["hello", "world"]`。 **程式碼線索** ```typescript= function createGenericStringArray(str1: string, str2: string): Array<string> { return [str1,str2] } // 使用這個函式 const stringArray = createGenericStringArray("hello", "world"); console.log(stringArray); // 輸出: ["hello", "world"] ``` ### **題目二:泛型函式**-練習泛型 `<T>` 用法 **函式名稱** `identity` **輸入** 一個型別參數 **`value`**。 **輸出** 直接回傳輸入的 **`value`**。 **範例** 輸入一個數字 **`5`**,函式回傳 **`5`**;輸入一個字串 **`"hello"`**,函式回傳 **`"hello"`**。 **程式碼線索** ```typescript= // 補上型別參數 function identity<T>(value:T):T { return value; } // 使用這個函式 const number = identity(5); console.log(number); // 輸出: 5 const string = identity("hello"); console.log(string); // 輸出: "hello" ``` ### 題目三:元組元素交換 **函式名稱** `swapElements` **輸入** 一個包含兩個不同型別元素的元組(Tuple),例如 **`["hello", 10]`**。 **輸出** 元素位置交換後的新元組,例如 **`[10, "hello"]`**。 **範例** 輸入元組 **`["hello", 10]`**,函式回傳的元組為 **`[10, "hello"]`**。 **程式碼線索** ```typescript= function swapElements<T,U>(tuple:[T,U]):[U,T]{ return [tuple[1], tuple[0]]; } // 使用這個函式 const swappedTuple = swapElements(["hello", 10]); console.log(swappedTuple); // 輸出: [10, "hello"] ``` ### **題目四:使用泛型處理不同型別的陣列** **函式名稱** `processArray` **輸入** - 一個泛型陣列 **`array: Array<T>`**,其中 **`T`** 可以是 **`string`**、**`number`** 或 **`boolean`**。 - 一個泛型函式 **`process: (item: T) => T`**,用於對陣列中的每個元素進行處理。 **輸出** 一個經過處理的泛型陣列 **`Array<T>`**,包含經過函式 **`process`** 處理過的所有元素。 **範例** 1. 輸入字串陣列 **`["apple", "banana"]`** 和一個將每個字串轉為大寫的函式,函式回傳陣列為 **`["APPLE", "BANANA"]`**。 2. 輸入數字陣列 **`[1, 2, 3]`** 和一個將每個數字加倍的函式,函式回傳陣列為 **`[2, 4, 6]`**。 3. 輸入布林陣列 **`[true, false, true]`** 和一個將每個布林值取反的函式,函式回傳陣列為 **`[false, true, false]`**。 **模擬程式碼** ```typescript= function processArray<T>(array:T[], process:(item:T)=> T ):T[]{ return array.map((item)=>{ return process(item) }); } // 使用這個函式 const processedStrings = processArray(["apple", "banana"], (s) => s.toUpperCase()); console.log(processedStrings); // 輸出: ["APPLE", "BANANA"] ``` ###### 參考:https://www.typescriptlang.org/docs/handbook/2/functions.html --- ## 🏅 [Day 10 - Interface V.S. Type](https://hackmd.io/Q8U3sTfuSROMsNG7QlA5Yw) ### 題目:Interface 與 Type 的使用時機是何時呢? --- ## [🏅 Day 9 - interfaces 延伸功能介紹](https://hackmd.io/WGPyU7IRRBOXm4fUpLdp5Q) ### 單選題 1. 哪一個關鍵字用於 TypeScript 中的介面擴展? A. merge <span style="color:crimson">B. extend</span> C. implements D. combine 2. 當兩個擁有相同名稱的介面出現在同一作用域中時,TypeScript 會怎麼做? A. 產生錯誤 B. 忽略其中一個 <span style="color:crimson">C. 合併它們</span> D. 重命名它們 3. 在 TypeScript 中,介面合併(Interface Merging)通常用於什麼情況? A. 當需要重新命名 interface 時 <span style="color:crimson">B. 當需要向現有介面添加更多屬性</span> C. 當需要創建全新的介面 4. 下面哪種說法正確描述了 TypeScript 中的介面擴展(Interface Extending)? <span style="color:crimson">A. 它允許一個介面從另一個介面繼承屬性和方法。</span> B. 它允許合併兩個具有不同名稱的介面。 --- ## [🏅 Day 8 - 型別別名(type)](https://hackmd.io/wZkwshenSu2vshb-E07tYg) ### 單選題 1. 在 TypeScript 中,型別別名(Type Aliases)的使用是為了什麼目的? A. 為了讓變數名稱更短 B. 為了創建新的型別 <span style="color:crimson">C. 為了給已存在的型別一個新名稱,並可用於建立複雜型別結構</span> D. 僅用於數字和字符串型別 2. 條件型別(Conditional Types)的一般形式是什麼? <span style="color:crimson">A. A extends B ? C : D</span> B. A && B ? C : D C. A ? B : C D. A || B ? C : D 3. 下面哪個是有效的型別別名宣告? A. type example = 1; B. type example = 'string'; <span style="color:crimson">C. type example = string;</span> ### **開發題:圖書租借管理系統** #### **任務解說:** 真實世界遇到的事情,其實遠遠比 Dcard、PTT 上的軟體工程師上鬼故事還要來得可怕 你現在就遇到了,當初圖書館的技術長信誓旦旦和你說,它們系統有導入 TypeScript 結果正式報到後你才發現,接手的是毫無可讀性的 JavaScript 程式碼,你很勉強得看出來,某段程式邏輯大概是在做圖書館的租借功能系統 你嘆了口氣後,決定先寫辭職信...不對,決定先暖暖身,一步步將 JS 改成 TypeScript 此時你可以開始嘗試: 1. 梳理資料結構,先從定義型別,將資料格式一一拆成型別別名(Type Aliases)~ 2. 各函式的 if else 巢狀裡面太可怕 3. 租借、歸還邏輯好像有機會將共用的抽離出來 [CodePen](https://codepen.io/YCLu/pen/ExMWyVJ) --- ## [🏅 Day 7 - 介面(interfaces)](https://hackmd.io/72ocxNDdSUmk6DODB48PGw) ### 單選題 1. **在 TypeScript 中,interface 主要用於:** A. 定義函數的返回值 B. 儲存資料 <span style="color:crimson">C. 定義物件的形狀</span> D. 計算數值 2. **在 TypeScript 的 interface 中,可選屬性是如何表示的?** <span style="color:crimson">A. 使用前綴符號 **`?`**</span> B. 使用前綴符號 **`#`** C. 使用後綴符號 **`!`** D. 使用後綴符號 **`^`** 3. **TypeScript 的 interface 可以用於哪種情況?** A. 定義一個變數的數值 <span style="color:crimson">B. 管理複雜的資料結構</span> C. 進行數學運算 D. 設定程式的背景顏色 ### 開發任務:醫院病患和預約管理系統 #### 目標 前工程師寫到一半烙跑了,所以你才有機會得到這份工作~ヽ(́◕◞౪◟◕‵)ノ 你的任務是接手他的糙 Code,來設計醫院病患和預約管理系統。 #### 任務描述 1. **定義介面** - **`Patient`** 介面:應包含病患的姓名(**`name`**)、年齡(**`age`**)、性別(**`gender`**)和病歷號碼(**`medicalRecordNumber`**)。 - **`Appointment`** 介面:應包含預約的日期(**`date`**)、時間(**`time`**)、醫生姓名(**`doctorName`**)和病患病歷號碼(**`patientMedicalRecordNumber`**),用來關聯病患的病歷號碼。 2. **實作資料結構** - 建立一個 **`patients`** 陣列,用於儲存 **`Patient`** 物件。 - 建立一個 **`appointments`** 陣列,用於儲存 **`Appointment`** 物件。 3. **開發功能** - 實作函式 **`addPatient`** 來添加新病患到 **`patients`** 陣列。 - 實作函式 **`scheduleAppointment`** 來為存在的病患安排新的預約,並加入到 **`appointments`** 陣列。 - 實作函式 **`cancelAppointment`** 來取消現有的預約。 - 實作函式 **`listAppointments`** 來列出特定病患的所有預約。 [CodePen](https://codepen.io/YCLu/pen/mdoRjyO) --- ## [🏅 Day 6 - 列舉型別(Enum)](https://hackmd.io/2Zdma_6ySry2nIhDlHSp4w) ### 選擇題 請觀察以下情境,並推斷他適合哪種型別格式: 1. 情境:你需要儲存不同的使用者角色,如「管理員」、「使用者」和「訪客」。這些角色是固定的且有特定的名稱。 <span style="color:crimson">A. 列舉 (Enum)</span> B. 元組 (Tuple) C. 陣列 (Array) 2. 情境:你正在開發一個函式,需要回傳一個包含經度和緯度的地理座標。 A. 列舉 (Enum) <span style="color:crimson">B. 元組 (Tuple)</span> C. 陣列 (Array) 3. 情境:你需要一個儲存全台灣各家庭的數據資料,例如每個家庭的總年收入。 A. 列舉 (Enum) B. 元組 (Tuple) <span style="color:crimson">C. 陣列 (Array)</span> 4. 情境:你需要表示一週的七天,每天都有一個特定的名稱。 <span style="color:crimson">A. 列舉 (Enum)</span> B. 元組 (Tuple) C. 陣列 (Array) 5. 情境:你需要追蹤一個電子商務網站上的產品類別,這些類別已經固定,不會隨時間而更改。 <span style="color:crimson">A. 列舉 (Enum)</span> B. 元組 (Tuple) C. 陣列 (Array) ### 開發題 #### **題目標題: 設計一個訂單處理系統** **情境描述:** 你正在開發一個電子商務系統,需要處理不同階段的訂單。為了更好地追蹤和管理訂單,你決定使用 TypeScript 的 **`enum`** 來表示訂單的各個處理階段。 **任務:** 1. 定義一個名為 **`OrderStatus`** 的 **`enum`**,其中包括以下狀態:待處理(Pending)、運送中(Shipping)、已送達(Delivered)、已取消(Cancelled)。 2. 建立一個函式,名稱為**`changeOrderStatus`**,藉此更新訂單狀態 - 參數:訂單 ID (**`orderId`**) 和新的訂單狀態 (**`newStatus`**)。 - 回傳:無(僅在控制台印出更新訊息)。 [CodePen](https://codepen.io/YCLu/pen/JjzEYzW) --- ## [🏅 Day 5 - 元組與聯合型別](https://hackmd.io/6ZDlR8naRBeauMVVNa-hhg) ### 單選題 **題目一:下列哪個選項正確描述了元組?** B - A. 元組是一種無序的資料結構 - B. 元組可以包含不同類型的值 - C. 元組的長度可以動態調整 - D. 元組的元素可以被修改 **題目二:以下哪個描述最準確地表示 TypeScript 中的「聯合型別」?** A - A. 聯合型別是一種將多個不同型別組合成一個型別的方式。 - B. 聯合型別是一種用於表示陣列的型別。 - C. 聯合型別是一種用於表示物件的型別。 **題目三:當我們想要表示多個不同型別的選項,並將它們合併成一個型別,我們應該使用什麼 TypeScript 功能?** B A. 元組 B. 聯合型別 **題目四:以下哪個 TypeScript 寫法表示一個元組(包含姓名和年齡)?** A ```tsx! const person: [string, number] = ["John", 30];// A const person: [string] = ["John", 30];// B const person: { name: string; age: number } = { name: "John", age: 30 };// C const person: (string | number)[] = ["John", 30];// D ``` **題目五:以下哪個 TypeScript 寫法表示一個聯合型別(可以是字串或數字)?** B ```tsx const value: string = "Hello"; // A const value: string | number = "Hello"; //B const value: (string | number)[] = ["Hello", 42]; //C const value: { text: string } = { text: "Hello" }; //D ``` **題目六:以下哪個 TypeScript 寫法表示一個函式的型別註釋(接受兩個數字並返回它們的和)?** A ```typescript const add = (a: number, b: number): number => a + b;//A function add(a: number, b: number) { //B return a + b; } const add: (a: number, b: number) => number = (a, b) => a + b; //C const add = (a, b) => a + b; //D ``` ### 開發題 [CodePen](https://codepen.io/YCLu/pen/qBvaeaK) --- ## [🏅 Day 4 - 陣列與物件](https://hackmd.io/a7dcRiVjT2ySsqddBKYzgw) ### 單選題 1. 在 TypeScript 中,以下哪個是正確宣告數字陣列的方式? A. let numbers = [1, 2, 3]; <span style="color:crimson">B. let numbers: number[] = [1, 2, 3];</span> C. let numbers: Array = [1, 2, 3]; D. let numbers: [number] = [1, 2, 3]; 2. 以下哪種方法可以用來向 TypeScript 陣列中添加新元素? A. append() <span style="color:crimson">B. push()</span> C. add() D. insert() 3. 如何宣告一個包含字串和數字的 TypeScript 陣列? A. let values: [string, number] = ["Hello", 5]; <span style="color:crimson">B. let values: (string | number)[] = ["Hello", 5];</span> C. let values: Array<string, number> = ["Hello", 5]; D. let values: string & number[] = ["Hello", 5]; 4. 在 TypeScript 中,pop() 方法的用途是什麼? A. 刪除陣列的第一個元素。 <span style="color:crimson">B. 刪除陣列的最後一個元素。</span> C. 在陣列的開頭添加一個元素。 D. 在陣列的末尾添加一個元素。 5. 以下哪個是 TypeScript 中宣告多維陣列的正確方式? <span style="color:crimson">A. let matrix: number[][] = [[1, 2], [3, 4]];</span> B. let matrix: Array<number> = [[1, 2], [3, 4]]; C. let matrix: number[] = [[1, 2], [3, 4]]; D. let matrix: [number, number][] = [[1, 2], [3, 4]]; ### 開發題目 1. 寫一個 calculateSum 函式,該函式接受一個數字陣列作為參數並回傳它們的總和。 ```typescript= function calculateSum(arr:number[]):number{ return arr.reduce((a,c)=>a+c,0) } ``` 2. 寫一個 findMaxValue 函式,參數可以接受包含不同數字的數字陣列,並 return 找出其中的最大值。 ```typescript= function findMaxValue(arr:number[]):number{ return Math.max(...arr) } ``` 3. 寫一個 mergeArrays 函式, 來合併兩個相同型別的字串陣列,並回傳一個包含兩個陣列所有元素的新陣列。 ```typescript= function mergeArrays(strArr1:string[], strArr2:string[]):string[]{ return [...strArr1, ...strArr2] } ``` --- ## [🏅 Day 3 - 函式](https://hackmd.io/BnYA9ZERRumzH0OUIFu_hw) ### 單選題 1. TypeScript 中,函式陳述式的主要特點是什麼? A. 可以被賦值給變數 <span style="color:crimson">B. 必須要有函式名稱</span> C. 都必須要回傳 void D. 不可以有回傳值 2. 在 TypeScript 中,函式參數的型別註釋主要作用是什麼? A. 指定函式執行的時間 <span style="color:crimson">B. 定義函式的參數和回傳值的型別</span> C. 確定函式的名稱 D. 調整函式的性能 3. 以下哪個選項正確定義了一個 TypeScript 函式,該函式接受兩個 number 類型的參數並回傳一個 number? A. `function add(x, y) { return x + y; }` <span style="color:crimson">B. `const add = (x: number, y: number) => x + y;`</span> C. `let add = function(x, y) { return x + y; }` D. `add(x: number, y: number): number { return x + y; }` 4. 如果一個 TypeScript 函式不回傳任何值,它的回傳型別應該是什麼? A. number B. string <span style="color:crimson">C. void</span> D. boolean ### 實做題 #### 設計一個 multiply 函式陳述式,設計兩個 number 型別的參數,並回傳它們的乘積。 ```typescript function multiply(a:number,b:number):number{ return a*b } ``` #### 宣告一個 concatStrings 變數,並賦值匿名箭頭函式,以符合函式表達式,設計兩個 string 型別的參數,並將它們連接起來。 ```typescript const concatStrings = (a:string, b:string):string => { return a+b } ``` #### 設計一個函式 isGreaterThanTen 函式陳述式,設計一個 number 型別的參數,並檢查該數字是否大於 10,回傳 boolean 值。 ```typescript function isGreaterThanTen(num:number):boolean{ return num>10 } ``` ### 面試題(選作) #### 使用函式陳述式、函式表達式的時機點是什麼時候? (answered by ChatGpt) - **函式陳述式**:通常在程式碼的頂層或區塊內部使用。它們可以在程式碼中的任何位置宣告,而它們的宣告會被提升(hoisted)至當前作用域的頂部。 > ###### Function declarations are typically used at the top level or within a block. They can be declared at any point in the code, as they are hoisted to the top of their current scope. - **函式表達式**:通常在運行時(runtime)進行宣告,並且可以存儲在變數中。它們在程式碼中的位置很重要,因為它們不會被提升,必須在宣告之後才能使用。 > Function expressions are typically declared at runtime and can be stored in variables. Their position in the code is crucial, as they are not hoisted and must be declared before use. --- ## [🏅 Day 2 - 原始型別、型別註釋、型別推斷](https://hackmd.io/mCNaaIq1TTiOlv4OcDC85w) ### 題目一:原始型別介紹 #### 程式實做題 1. 請使用字串型別宣告一個名為 name 的變數,並將其設定為你的名字。 ```typescript let name:string = 'YC' ``` 2. 請使用數字型別宣告一個名為 age 的變數,並將其設定為你的年齡。 ```typescript let age:number = 18 const foreverAge:number = 18 // ← 永遠 18 歲啦!!! ``` 3. 請使用布林型別宣告一個名為 isStudent 的變數,並將其設定為你是否是學生(是為 true,否為 false)。 ```typescript let isStudent:boolean = false ``` 4. 請使用 any 型別宣告一個名為 data 的變數,並將其設定為任意值。 ```typescript let anyData:any = 'any' ``` ### TypeScript 型別註釋與型別推斷 #### 單選題: 1. 型別註釋是強制一定要加上的嗎?B A. 是 B. 否 2. 型別推斷基於什麼來推斷變數的型別?A A. 初始化值 B. 函式參數 3. 型別推斷可以幫助我們省略哪些型別註釋?D A. 字串型別註釋 B. 數字型別註釋 C. 函式型別註釋 D. 所有型別註釋 #### 開發題目: 1. 請使用型別註釋宣告一個變數 score,並將其設置為數字型別,初始值為 80。 ```typescript let score:number = 80 ``` 2. 請使用型別推斷宣告一個變數 message,並將其設置為字串型別,初始值為 “Hello, TypeScript!”。 ```typescript let message = "Hello, TypeScript!" ``` 3. 請使用型別註釋宣告一個變數 fullName,並將其設置為字串型別,初始值為你的姓名。 ```typescript let fullName:string = 'YC' ``` #### 面試題(選做) 你會如何判斷何時用型別推論或型別註釋? - 型別推論:初始化時或型別明顯時 - 型別註釋:無法自動推斷時 --- ## [🏅 Day 1 - TypeScript 簡介](https://hackmd.io/uaB7XYeDQXCW8-HPzl30yQ) ### 題目一:TypeScript 介紹,五道單選題 TypeScript 是什麼類型的程式語言?2 1. 動態型別語言 2. 靜態型別語言 3. 混合型別語言 TypeScript 是基於哪種程式語言的超集? 3 1. Python 2. Java 3. JavaScript TypeScript 的主要優勢是什麼?3 1. 更高的執行效能 2. 更簡潔的語法 3. 更好的可維護性和可擴展性 TypeScript 提供了哪種功能來進行型別檢查?3 1. 編譯時型別檢查 2. 執行時型別檢查 3. 靜態型別檢查 TypeScript 可以直接運行於瀏覽器中嗎?2 1. 可以 2. 不可以

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    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

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully