zoukankan      html  css  js  c++  java
  • TypeScript

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

    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 进行定义。

  • 相关阅读:
    API
    API
    for in
    event flow
    object
    Report of program history
    正则表达式
    伪类与伪元素
    Position
    js学习之原型(补充)
  • 原文地址:https://www.cnblogs.com/xjy20170907/p/10882758.html
Copyright © 2011-2022 走看看