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 ...
随机推荐
- (五)JPA - 原生SQL实现增删改查
6.原生SQL JPA除了对JPQL提供支持外,还对原生SQL语句也提供了支持.下面小节一起来看看吧. 6.1 查询单个 示例代码: @Test public void getSingle() { E ...
- 配置DNS域名解析服务
概: DNS技术作为互联网基础设施中的重要一环,为用户提供不间断.稳定且快速的域名查询服务,保证互联网正常运转.在互联网中,用户基本上都是基于DNS服务,使用域名访问网络上的计算机,DNS服务是我 ...
- 分支结构中的if-else(条件判断结构)
一.三种结构 第一种: if(条件表达式){ 执行表达式}第二种:二选一 if(条件表达式){ 执行表达式1}else{ 执行表达式2}第三种:n选一 if(条件表达式){ 执行表达式1}else i ...
- Java云原生崛起微服务框架Quarkus入门实践
@ 目录 概述 定义 GraalVM简介 为何使用 特性 官方性能 实战 入门示例 步骤 安装GraalVM 创建quarkus工程 Idea导入项目 Idea运行和调试 打包成普通的Jar 打包成依 ...
- 【UML】统一建模语言
如果是准备学习设计模式的同学,可以只了解类图相关的知识 而如果是在准备软件设计师考试的同学,或许会对你有点帮助 正在施工...... 参考博客:https://blog.csdn.net/unique ...
- AgileBoot - 如何集成内置数据库H2和内置Redis
本项目地址: github: https://github.com/valarchie/AgileBoot-Back-End gitee: https://gitee.com/valarchie/Ag ...
- .Net 文件导出下载
//1.首先要有文件路径 2.要知道文件扩展名 3.根据扩展名在Provider Map对应的contentType 4.return FileSteam public IActionResult E ...
- 0基础90分钟会用PS——GenJi笔记
数码图像的相关基础概念 1.位图和矢量图 位图 也叫点阵图像,位图使用也称像素的一格一格的小点来描述图像,图放大后我们可以看到像素点 矢量图 根据几何特性来绘制图形,用线段和曲线描述图像,可以是一个一 ...
- SoringCloud(四) - 微信获取用户信息
1.项目介绍 2.微信公众平台 和 微信开放文档 2.1 微信公众平台 2.1.1 网址链接 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?ac ...
- rocky二进制安装mysql8.0
(ubuntu的有点问题) 点击查看代码 #!/bin/bash Version=`cat /etc/os-release |awk -F'"| ' '/^NAME/{print $2}'` ...