[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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值