• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Typescript]NarrowtheunknownTypewithTypeScript'sAssertionFunctions

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

This lesson introduces assertion functions which let us narrow the type of a variable or property for the remainder of the containing scope. We're going to learn how to create an assertion function by using the asserts keyword in the function signature. In particular, we're going to focus on narrowing the unknown type to a more specific type.

'assert' will throw if the condition is not match.

function assert(condition: unknown, name?: string): asserts condition {
// Recommended using falsy condition
if (!condition) { throw TypeError(`${name} is not a number`) } } function assertIsNumber(value: unknown, name?: string): asserts value is number{ if (typeof value !== "number") { throw TypeError(`${name} is not a number`) } } function add(x: unknown, y: unknown): number { assert(typeof x === "number", "x"); assert(typeof y === "number", "y"); return x + y; } function multiply(x: unknown, y: unknown) { assertIsNumber(x,"x"); assertIsNumber(y, "y"); return x * y; } multiply(10, 5);

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
如何在TypeScript/JavaScript项目里引入MD5校验和发布时间:2022-07-22
下一篇:
TypeScript类型检查机制发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap