08-TypeScript-中-is-关键字

本文介绍了TypeScript中的is关键字用于类型保护的机制。通过is关键字定义的函数可以缩小变量的类型范围,仅在if语句后的块级作用域生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TypeScript 中 is 关键字

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

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

function isString(test: any): test is string {
  return typeof test === 'string'
}

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

function isString(test: any): boolean {
  return typeof test === 'string'
}

使用 is 类型保护

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

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 后的块级作用域中生效。

原文引自:金点网络/数媒派 作者:jamin

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值