TypeScript 入门教程
  • TypeScript 入门教程
  • 进阶
    • 类与接口
    • 类
    • 声明合并
    • 装饰器
    • 枚举
    • 扩展阅读
    • 泛型
    • 字符串字面量类型
    • 元组
    • 类型别名
  • 基础
    • 任意值
    • 内置对象
    • 声明文件
    • 原始数据类型
    • 类型断言
    • 类型推论
    • 数组的类型
    • 函数的类型
    • 对象的类型——接口
    • 联合类型
  • 工程
    • 编译选项
    • 代码检查
  • 简介
    • 安装 TypeScript
    • Hello TypeScript
    • 什么是 TypeScript
    • why-typescript
  • 感谢
Powered by GitBook
On this page
  • 简单的例子
  • 参考

Was this helpful?

  1. 进阶

字符串字面量类型

Previous泛型Next元组

Last updated 4 years ago

Was this helpful?

字符串字面量类型用来约束取值只能是某几个字符串中的一个。

简单的例子

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

handleEvent(document.getElementById('hello'), 'scroll');  // 没问题
handleEvent(document.getElementById('world'), 'dblclick'); // 报错,event 不能为 'dblclick'

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

上例中,我们使用 type 定了一个字符串字面量类型 EventNames,它只能取三种字符串中的一种。

注意,类型别名与字符串字面量类型都是使用 type 进行定义。

参考

  • ()

Advanced Types # Type Aliases
中文版