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

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 

以上是关于[Typescript] Specify Exact Values with TypeScript’s Literal Types的主要内容,如果未能解决你的问题,请参考以下文章

Python eval,exac,compile

Remove VirtualPortGroup Specify vSwitch

Specify Computed Columns in a Table

CV项目调试CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT问题

Verilog中的specify block和timing check

vsftp 331 Please specify the password.