zoukankan      html  css  js  c++  java
  • [Typescript] Specify Exact Values with TypeScript’s Literal Types

    A literal type is a type that represents exactly one value, e.g. one specific string or number. You can combine literal types with union types to model a finite set of valid values for a variable. In this lesson, we explore the all kinds of literal types in TypeScript:

    • String literal types
    • Numeric literal types
    • Boolean literal types
    • Enum literal types

    First String literal types:

    let autoComplete: "on" | "off" | "ON" | "OFF";
    autoComplete = "On" // case sensitive, compiler error

    Number literal types:

    type NumberBase = 2 | 8 |10 | 16;
    let base: NumberBase;
    base = 2;
    base = 4; // error 

    Boolean literal types:

    let autoFocus: true = true;
    autoFocus = false; // error

    Enum literal types:

    enum Protocols {
        HTTP,
        HTTPS,
        FTP
    }
    
    type HyperTextProtocol = Protocols.HTTP | Protocols.HTTPS;
    
    let protocol: HyperTextProtocol;
    protocol = Protocols.HTTP;
    protocol = Protocols.HTTPS;
    protocol = Protocols.FTP; // error
  • 相关阅读:
    2019第二周作业
    2019 编程总结
    寒假作业2编程总结
    2018秋季学习总结
    喜欢的老师
    人生路上对我影响最大的三位老师
    自我介绍
    抓老鼠啊~亏了还是赚了?
    币值转换
    打印沙漏
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9676021.html
Copyright © 2011-2022 走看看