布尔文字类型:Boolean Literal Types
true
或false
可以作为类型和值进行初始化。
const TRUE: true = true;
const FALSE: false = false;
不能反过来:
// 报错
const TRUE: false = true;
const FALSE: true = false;
boolean
类型等同于true | false
的联合类型。
一个例子:
布尔文字类型很少单独使用,但它在与标记的联合类型和基于控制流的类型分析结合时很有用。如,有一个消息,若是成功消息,则有value值为它本身。若是失败消息,则有error为失败信息。
类型定义如下:
type Result<T> =
| {
success: true; value: T }
| {
success: false; error: string };
以要验证输入的内容是否是合格的邮箱为例,方法如下:(输入为邮箱的话,value的T为string)
function parseEmailAddress(input: string | null | undefined): Result<string> {
// 为null或undefined
if (!input) {
// 返回错误信息
return {
success: false,
error: "Input is empty!",
};
}
// 正则表达式验证此邮箱格式是否正确:[email protected]
if (!/^\S+@\S+\.\S+$/.test(input)) {
// 不正确
return {
success: false,
error: "Input is invalid",
};
}
return {
success: true,
value: input,
};
}
这里的正则表达式验证合格的邮箱:[email protected]
正则表达式为:/^\S+@\S+\.\S+$/
/^
:表示开头
\S
:非空白就匹配
+@
:前面的加上@
\.
:.
的转义表示
$/
:表示结束扫描二维码关注公众号,回复: 17155640 查看本文章
调用上面的方法:
var parsed = parseEmailAddress("[email protected]");
此时返回:是没有error属性的。
{
success: true, value: '[email protected]' }
数字文字类型:Numeric Literal Types
声明:
let zeroOrOne: 0 | 1;
zeroOrOne = 0;
// OK
zeroOrOne = 1;
// OK
zeroOrOne = 2;
// Error: Type '2' is not assignable to type '0 | 1'
方法:
function getPort(scheme: "http" | "https"): 80 | 443 {
switch (scheme) {
case "http": {
return 80;
}
case "https": {
return 443;
}
}
}
枚举文字类型:Enum Literal Types
const enum HttpPort {
Http = 80,
Https = 443,
}
function getScheme(port: HttpPort.Http): "http";
function getScheme(port: HttpPort.Https): "https";
function getScheme(port: HttpPort): "http" | "https" {
switch (port) {
case HttpPort.Http: {
return "http";
}
case HttpPort.Https: {
return "https";
}
}
}
const scheme = getScheme(HttpPort.Http);
// Type "http"
上面的TS代码编译为JS后:
function getScheme(port) {
switch (port) {
case 80:
return "http";
case 443:
return "https";
}
}
var scheme = getScheme(80);