前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Note·TypeScript 中 is 关键字

Note·TypeScript 中 is 关键字

作者头像
数媒派
发布2022-12-01 11:31:10
3540
发布2022-12-01 11:31:10
举报
文章被收录于专栏:产品优化

本文为个人学习摘要笔记。 原文地址:TypeScript 中的 is

TypeScript 里有类型保护机制。要定义一个类型保护,我们只要简单地定义一个函数,它的返回值是一个类型谓词

代码语言:javascript
复制
function isString(test: any): test is string {
  return typeof test === 'string'
}

上述写法与写一个返回值为 boolean 值函数的区别在哪里呢?

代码语言:javascript
复制
function isString(test: any): boolean {
  return typeof test === 'string'
}

使用 is 类型保护

代码语言:javascript
复制
function isString(test: any): test is string {
  return typeof test === 'string'
}

function example(foo: any) {
  if (isString(foo)) {
    console.log('it is a string' + foo)
    console.log(foo.length) // string function
    // 如下代码编译时会出错,运行时也会出错,因为 foo 是 string 不存在 toExponential 方法
    console.log(foo.toExponential(2))
  }
  // 编译不会出错,但是运行时出错
  console.log(foo.toExponential(2))
}
example('hello world')

返回值为 boolean

代码语言:javascript
复制
function isString(test: any): boolean {
  return typeof test === 'string'
}

function example(foo: any) {
  if (isString(foo)) {
    console.log('it is a string' + foo)
    console.log(foo.length) // string function
    // foo 为 any,编译正常。但是运行时会出错,因为 foo 是 string 不存在 toExponential 方法
    console.log(foo.toExponential(2))
  }
}
example('hello world')

总结

  • 在使用类型保护时,TS 会进一步缩小变量的类型。例子中,将类型从 any 缩小至了 string;
  • 类型保护的作用域仅仅在 if 后的块级作用域中生效。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用 is 类型保护
  • 返回值为 boolean
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档