# 字符串字面量類型
字符串字面量類型用來約束取值只能是某幾個字符串中的一個。
## 簡單的例子
```ts
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](http://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types)([中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Advanced%20Types.html#字符串字面量類型))
---
- [上一章:類型別名](type-aliases.md)
- [下一章:元組](tuple.md)