TypeScript 3.7 RC & Assertion Functions
2024-10-19 20:20:33
TypeScript 3.7 RC & Assertion Functions
assertion functions, assert
https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-rc/#assertion-functions
function yell(str) {
assert(typeof str === "string");
return str.toUppercase();
// ~~~~~~~~~~~
// error: Property 'toUppercase' does not exist on type 'string'.
// Did you mean 'toUpperCase'?
}
function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
throw new AssertionError(msg)
}
}
function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new AssertionError("Not a string!");
}
}
// Here asserts val is string ensures that after any call to assertIsString, any variable passed in will be known to be a string.
function yell(str: any) {
assertIsString(str);
// Now TypeScript knows that 'str' is a 'string'.
return str.toUppercase();
// ~~~~~~~~~~~
// error: Property 'toUppercase' does not exist on type 'string'.
// Did you mean 'toUpperCase'?
}
type predicate signatures
function isString(val: any): val is string {
return typeof val === "string";
}
function yell(str: any) {
if (isString(str)) {
return str.toUppercase();
}
throw "Oops!";
}
assertion signatures
function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
if (val === undefined || val === null) {
throw new AssertionError(
`Expected 'val' to be defined, but received ${val}`
);
}
}
refs
https://www.cnblogs.com/xgqfrms/tag/TypeScript 3.7 RC/
xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
最新文章
- iOScollectionView广告无限滚动(Swift实现)
- ";SQL Server does not handle comparison of NText, Text, Xml, or Image data types.";
- 可重入锁 公平锁 读写锁、CLH队列、CLH队列锁、自旋锁、排队自旋锁、MCS锁、CLH锁
- B树系列
- C++语言-03-类与对象
- 在windows下用cygwin和eclipse搭建cocos2dx的android开发环境
- crud springmvc
- 1930. Ivan&#39;s Car(spfa)
- Codeforces Bubble Cup 8 - Finals [Online Mirror]H. Bots 数学
- python 调用函数
- 08 - 删除vtkDataObject中的SetWholeExtent() 方法 VTK 6.0 迁移
- bash 变量使用技巧
- 2.x ESL第二章习题2.5
- AutoMapper IIS回收引发的 未将对象引用设置到对象实例
- win7远程桌面 连接不上(用户名与全名不匹配的问题)
- 使用addviewController()实现无业务逻辑跳转
- (后端)SQL SERVER 字符串按数字排序
- 微信小程序采坑(一)
- 140 - The 12th Zhejiang Provincial Collegiate Programming Contest(第三部分)
- [c/c++] programming之路(6)、ASCII码,数据类型、随机数、字符转换及拼接等
热门文章
- 在 ASP.NET Core 应用中使用 Cookie 进行身份认证
- python 拼接字
- 高性能缓存 Caffeine 原理及实战
- 十一:SpringBoot-事务管理
- idea中类注释和方法注释的设置
- 使用xshell连不上ubuntu14.04
- 2019 Multi-University Training Contest 4.Divide the Stones(贪心)
- 洛谷P4719 【模板】";动态 DP";&;动态树分治
- Codeforces Round #663 (Div. 2) C. Cyclic Permutations (构造,图?)
- spark 一、编程指南