码迷,mamicode.com
首页 > 其他好文 > 详细

[Typescript] Specify Exact Values with TypeScript’s Literal Types

时间:2018-09-19 19:45:13      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:complete   sso   str   als   ali   ase   explore   exactly   mode   

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

 

[Typescript] Specify Exact Values with TypeScript’s Literal Types

标签:complete   sso   str   als   ali   ase   explore   exactly   mode   

原文地址:https://www.cnblogs.com/Answer1215/p/9676021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!