TypeScript: Type predicates
TypeScript 类型判断--合理的使用 is
和 type
- 这篇文章主要写在使用函数的时候确保你的参数类型正确的规范的建议。
写在最前面
- 最开始写 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 在判断的时候还是抛出了错误提示。。