TypeScript 类型判断--合理的使用 is 和 type

本文介绍了如何在 TypeScript 中使用类型断言函数(如 is 和 type)来合理地判断和缩小参数类型。通过示例展示了如何在函数内部确保参数类型正确,并避免类型错误。通过 isString 函数演示了如何明确告诉 TypeScript 参数是字符串类型,以及如何在处理可能的数值集合时,使用联合类型缩小参数类型范围。
摘要由CSDN通过智能技术生成

TypeScript: Type predicates

TypeScript 类型判断--合理的使用 istype

  • 这篇文章主要写在使用函数的时候确保你的参数类型正确的规范的建议。

写在最前面

  • 最开始写 typescript 最困难的就是各种类型的判断,最近浏览 jsFeed 的时候看到一篇不错的文章,然后自己翻译了一下分享给大家。
  • 文章中的翻译都是义译,没有逐字逐段,很多不正确的地方望指出。

Type predicates in TypeScript help you narrowing down your types based on conditionals. They’re similar to type guards, but work on functions. They way the work is, if a function returns true, change the type of the paramter to something more useful.

typescript 的类型断言帮助你更好的规范你的代码类型。类型断言一般在函数中使用(work on functions),来确保你的函数类型返回正确。

is 的使用场景

step 1

  • Let’s start with a basic example. Let’s say you have a function that checks if a certain value is of type string:
  • 来看一个栗子
function isString(s) {
  return typeof s === 'string';
}

复制代码

step 2

  • Use the isString function inside another function:
  • 在另外一个函数中使用上面的函数(isString())
function toUpperCase(x: unknown) {
  if(isString(x)) {
    x.toUpperCase(); // ⚡️ x is still of type unknown
  }
}
复制代码

TypeScript throws an error. We can be sure that x is of type string at this point. But since the validation is wrapped in a function, the type of x does not change (as opposed to type guards). Enter type predicates.

ts 抛出了一个错误提示,我们能确信 x 是在类型判断为 string 以后再进行 toupperCase().但是由于这个检验函数(isString)被包裹在 toUpperCase()函数中,ts 在判断的时候还是抛出了错误提示。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值