TypeScript 之 控制流分析(Control Flow Analysis)
控制流分析(Control Flow Analysis)
描述:
简单说就是:根据代码上下文可以推断出当前变量类型。
if 语法(If Statements)
const input = getUserInput()
input // string | number
if (typeof input === "string") {
input // string
}
const input = getUserInput()
input // string | number[]
if (input instanceof Array) {
input // number[]
}
const input = getUserInput()
input // string | {error: ...}
if ("error" in input) {
input // {error: ...}
}
const input = getUserInput()
input // number | number[]
if (Array.isArray(input)) {
input // number[]
}
表达式(Expressions)
const input = getUserInput()
input // string | number
const inputLength = (typeof input === "string" && input.length) || input
//&& input: string
识别联合(Discriminated Unions )
type JSONResponse = {status: 200, data: any}
| {status: 300, to: string}
| {status: 400, error: Error}
const response = getResponse()
response // JSONResponse switch(response.status) {
case 200: response.data
case 400: redirect(response.to)
case 500: response.error
}
类型保护(Type Guards)类型谓词(type predicates)
type Fish = { name: string; swim: () => string };
type Bird = { name: string; fly: () => string };
const fish: Fish = { name: "sharkey", swim: () => 'asd' }
const bird: Bird = { name: "noob", fly: () => 'asd' }
// 未使用类型谓词
function isFish(pet: Fish | Bird) {
return (pet as Fish).swim !== undefined;
}
const foo: Fish | Bird = Math.random() ? fish : bird;
if (isFish(foo)) {
// foo: Fish | Bird
foo.swim() // 不能调用,不确定是 Fish 类型
}
// 使用类型谓词
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
const foo: Fish | Bird = Math.random() ? fish : bird;
if (isFish(foo)) {
// foo: Fish
foo.swim() // ok
}
// 必须是当前函数签名中参数的名称(pet)。
// 如果特定类型与原始类型兼容(Fish 与 Fish | Bird),TypeScript 会将该变量缩小为该特定类型,不兼容会报错
const zoo: (Fish | Bird)[] = [getSmallPet(), getSmallPet(), getSmallPet()];
const underWater1: Fish[] = zoo.filter(isFish);
// 相当于
const underWater2: Fish[] = zoo.filter(isFish) as Fish[]; // 复杂的例子,谓词需要重复
const underWater3: Fish[] = zoo.filter((pet): pet is Fish => {
if (pet.name === "sharkey") return false;
return isFish(pet);
});
断言函数(Assertion Functions)
type SuccessResponse = {data: string}
type ErrorResponse = {msg: string}
class JSONResponse implements SuccessResponse {
constructor(public data: string) { }
}
function assertResponse(obj: SuccessResponse | ErrorResponse): asserts obj is ErrorResponse {
if (!(obj instanceof JSONResponse)) {
throw new Error("Not a success!")
}
}
const res = getResponse();
res // SuccessResponse | ErrorResponse
assertResponse(res) // 断言函数更改当前作用域
res // ErrorResponse
赋值(Assignment)
const data1 = { name: "Zagreus" }
const data2 = { name: "Zagreus" } as const
// data1: {name: string}
// data2: { readonly name: "Zagreus"}
class SuccessResponse { }
const response = getResponse()
const isSuccessResponse = response instanceof SuccessResponse
if (isSuccessResponse) {
response // SuccessResponse
}
let data: string | number = Math.random() ? "asd" : 123
data // string | number
data = "hello"
data // string
感谢观看,欢迎互相讨论与指导,以下是参考资料链接
TypeScript 之 控制流分析(Control Flow Analysis)的更多相关文章
- 南大《软件分析》课程笔记——Data Flow Analysis
南大<软件分析>--Data Flow Analysis @(静态分析) 目录 数据流分析概述 数据流分析应用 Reaching Definitions Analysis(may anal ...
- SSIS的 Data Flow 和 Control Flow
Control Flow 和 Data Flow,是SSIS Design中主要用到的两个Tab,理解这两个Tab的作用,对设计更高效的package十分重要. 一,Control Flow 在Con ...
- Control Flow 如何处理 Error
在Package的执行过程中,如果在Data Flow中出现Error,那么Data Flow component能够将错误行输出,只需要在组件的ErrorOutput中进行简单地配置,参考<D ...
- 关于Control flow
1.一个package包含一个control flow并且一个或多个data flow. (这个项目叫做 Integration services project,提供了三种不同类型的control ...
- Core Java Volume I — 3.8. Control Flow
3.8. Control FlowJava, like any programming language, supports both conditional statements and loops ...
- SSIS ->> Control Flow And Data Flow
In the Control Flow, the task is the smallest unit of work, and a task requires completion (success, ...
- Control Flow in Async Programs
Control Flow in Async Programs You can write and maintain asynchronous programs more easily by using ...
- A swift Tour(2) Control Flow
Control Flow 用 if 和 switch 来做条件语句,并且用for-in,for,while,和do-while做循环,条件和循环的括号是可以不写的,但是body外面的括号是必须写的 l ...
- [译]Stairway to Integration Services Level 9 - Control Flow Task Errors
介绍 在本文中,我们会实验 MaximumErrorCount和ForceExecutioResult 故障容差属性,并且还要学习Control Flow task errors, event han ...
- 《CS:APP》 chapter 8 Exceptional Control Flow 注意事项
Exceptional Control Flow The program counter assumes a sequence of values ...
随机推荐
- 域名服务DNSmasq搭建
假设该服务端主机ip是:192.168.80.100 服务端安装(yum方式) yum install dnsmasq -y # 配置系统文件 # cp /etc/resolv.conf /etc/r ...
- 使用Gitlab的CI/CD功能自动化推送docker镜像到Nexus仓库出现的问题
在服务器中可以直接使用命令行登录,推送docker镜像等 但是在使用Gitlab的CI/CD功能中,gitlab-ci.yml文件执行过程中出现如下错误: 原因分析: 服务器上之前使用命令行登陆过Ne ...
- Elasticsearch:如何调试集群状态 - 定位错误信息
文章转载自:https://blog.csdn.net/UbuntuTouch/article/details/108973356
- 1_Maven
一. 引言 1.1 项目管理问题 项目中jar包资源越来越多, jar包的管理越来越沉重 1.1.1 繁琐 要为每个项目手动导入所需的jar, 需要搜集全部的jar 1.1.2 复杂 项目中的jar如 ...
- python-绘图与可视化
python 有许多可视化工具,但本书只介绍Matplotlib.Matplotlib是一种2D的绘图库,它可以支持硬拷贝和跨系统的交互,它可以在python脚本,IPython的交互环境下.Web应 ...
- Flink WordCount入门
下面通过一个单词统计的案例,快速上手应用 Flink,进行流处理(Streaming)和批处理(Batch) 单词统计(批处理) 引入依赖 <!--flink核心包--> <depe ...
- 16.MongoDB系列之分片管理
1. 查看当前状态 1.1 查看配置信息 mongos> use config // 查看分片 mongos> db.shards.find() { "_id" : & ...
- 驱动开发:内核枚举ShadowSSDT基址
在笔者上一篇文章<驱动开发:Win10枚举完整SSDT地址表>实现了针对SSDT表的枚举功能,本章继续实现对SSSDT表的枚举,ShadowSSDT中文名影子系统服务描述表,SSSDT其主 ...
- laravel config()获取null
常规开发获取config值的是否发现获取值为null找了下文档,发现laravel是要把config注册到$app里面. 找到这个目录.加入这一行.就可以了
- 靶机: easy_cloudantivirus
靶机: easy_cloudantivirus 准备 下载靶机(Target):https://www.vulnhub.com/entry/boredhackerblog-cloud-av,453/ ...