首頁
學習紀錄
遊戲心得影視Life書單案件檔案
Side Projects委託作品與二創互動實驗場
Kurau
百百 BLOG
首頁
學習紀錄
遊戲心得影視Life書單案件檔案
Side Projects委託作品與二創互動實驗場
Kurau

Kurau Blog

「隨心而寫,真真假假,都是我」

一個記錄生活、輸出興趣的個人空間。
遊戲、影視、閱讀、學習……每一段體驗都值得留下文字。

頁面導覽

  • 學習紀錄
  • 遊戲心得
  • 影視Life
  • 書單
  • 委託作品與二創
  • Kurau
  • 合作邀請

找到我

歡迎來 Discord 找我聊天!

“曾經發生的事不可能忘記,只是暫時想不起來而已。”-《神隱少女》

© 2026 Kurau All rights reserved

面試考題

TypeScript 宣告

By Kurau·Updated 2026-05-31·3 分鐘閱讀

TypeScript 在宣告時用「冒號 :」加上型別來做型別註記(type annotation):

const x: number = 5;
let name: string = "Tom";
ts

很多時候不用手動寫,TypeScript 會**型別推斷(type inference)**自動推出:const x = 5 就已經是 number。

宣告物件型別:interface 與 type

複雜的型別可以用 interface 或 type 來命名後重複使用:

interface Person {
    name: string;
    age: number;
}

type Animal = {
    name: string;
    legs: number;
};

const tom: Person = { name: "Tom", age: 18 };
ts

兩者大部分情境可互換,主要差異:

interfacetype
擴充方式extends 繼承& 交集(intersection)
宣告合併✅ 同名會自動合併❌ 同名會報錯
適用範圍只能描述物件 / class 形狀任何型別(union、tuple、primitive 別名…)

經驗法則:描述物件或要被 class implements 用 interface;需要 union(type Status = "ok" | "error")或別名用 type。

泛型(Generics)

泛型才是用 < > 的地方 —— 它讓型別像「參數」一樣傳入,寫出對多種型別都通用、又不丟失型別資訊的程式碼:

function identity<T>(x: T): T {
    return x;
}

const a = identity<number>(5);   // a 是 number
const b = identity("hello");      // T 推斷成 string,b 是 string
ts

T 是型別變數,呼叫時才決定實際型別。也能用在 interface / type 上:

interface Box<T> {
    value: T;
}

const numBox: Box<number> = { value: 5 };
ts

可用 extends 對泛型加約束,例如 <T extends { id: number }> 限制 T 必須有 id。

常用 Utility Types

TypeScript 內建一批根據既有型別衍生新型別的工具:

interface User {
    id: number;
    name: string;
    email: string;
}

type PartialUser = Partial<User>;        // 所有欄位變成 optional
type UserName = Pick<User, "name">;       // 只取 name 欄位
type IdToName = Record<number, string>;   // { [key: number]: string }
ts
  • Partial<T>:把 T 的所有屬性變成可選,常用於更新(patch)場景。
  • Pick<T, K>:只挑出 T 中指定的幾個 key。
  • Record<K, V>:建立 key 為 K、value 為 V 的物件型別。

其他常見的還有 Omit、Required、Readonly,都是建立在泛型之上的衍生型別。

目錄

    ◆ 相關文章

    • TypeScript 特性 - Interface

      2026-06-02
    • Type 和 Interface的差別

      2026-05-09
    • Async function-Await 函式

      2026-06-02
    • throw Error用法

      2026-06-02
    ← 上一篇Stock Information 公司情報篇 (消息面、營運面、財務面)下一篇 →前端記錄 - 考題 (React TS JS)

    ◆ 關於作者

    Kurau

    個人寫作 / 創作的 SoT,記錄遊戲、影視、學習與生活。

    更多 Kurau 的文章