TypeScript 新手指南
  • 前言
  • 簡介
    • 什麼是 TypeScript
    • 安裝 TypeScript
    • Hello TypeScript
  • 基礎
    • 原始資料型別
    • 任意值
    • 型別推論
    • 聯合型別
    • 物件的型別——介面
    • 陣列的型別
    • 函式的型別
    • 型別斷言
    • 宣告檔案
    • 內建物件
  • 進階
    • 型別別名
    • 字串字面量型別
    • 元組
    • 列舉
    • 類別
    • 類別與介面
    • 泛型
    • 宣告合併
    • 延伸閱讀
  • 工程
    • 程式碼檢查
  • 感謝
Powered by GitBook
On this page
  • 簡單的例子
  • 參考

Was this helpful?

  1. 進階

字串字面量型別

Previous型別別名Next元組

Last updated 4 years ago

Was this helpful?

字串字面量 (String Literal) 型別用來約束取值只能是某幾個字串中的一個。

簡單的例子

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
    // do something
}

handleEvent(document.getElementById('hello'), 'scroll');  // 沒問題
handleEvent(document.getElementById('world'), 'dbclick'); // 報錯,event 不能為 'dbclick'

// index.ts(7,47): error TS2345: Argument of type '"dbclick"' is not assignable to parameter of type 'EventNames'.

上例中,我們使用 type 定了一個字串字面量型別 EventNames,它只能取三種字串中的一種。

注意,型別別名與字串字面量型別都是使用 type 進行定義。

參考

  • ()

Advanced Types # Type Aliases
中文版
上一章:型別別名
下一章:元組