Allen Yu Allen Yu
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
  • 开始

  • 基础

  • 进阶

    • 类型别名
    • 字符串字面量类型
      • 字符串字面量类型 (String Literal Types)
      • 简单的例子
      • 参考
    • 元组
    • 枚举
    • 类
    • 类与接口
    • 泛型
    • 声明合并
    • 工具类型
    • 编译配置
  • 实战

  • TypeScript
  • 进阶
2020-10-31
目录

字符串字面量类型

# 字符串字面量类型 (String Literal Types)

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

# 简单的例子

type EventNames = 'click' | 'scroll' | 'mouseover'

function handlerEvent(el: Element, event: EventNames) {
  console.log(event)
}

handlerEvent(document.querySelector('.btn'), 'click')
handlerEvent(document.querySelector('.link'), 'mouseover')

如果传递的事件名称不在 EventNames 内

handlerEvent(document.querySelector('.btn2'), 'mouseout')
// 类型“"mouseout"”的参数不能赋给类型“EventNames”的参数。ts(2345)

上面的 handlerEvent 函数,第二参数传递的是 mouseout 不在 EventNames 中,所以报错了

# 参考

  • TypeScript 入门教程 - 字符串字面量类型 (opens new window)
Last Updated: 3/30/2022, 1:20:25 AM
类型别名
元组

← 类型别名 元组→

最近更新
01
4 月第 2 周总结
04-17
02
工具类型
04-01
03
Google 搜索小技巧
03-28
更多文章>
Theme by Vdoing | Copyright © 2018-2022 Allen Yu
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式