TypeScript: Type predicates
is
和 type
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),来确保你的函数类型返回正确。
function isString(s) {
return typeof s === 'string';
}
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 在判断的时候还是抛出了错误提示。。
is
,这里让我们主动明确的告诉 ts ,在 isString() 这个函数的参数是一个 string。
// !!! 使用 is 来确认参数 s 是一个 string 类型
function isString(s): s is string {
return typeof s === 'string';
}
复制代码
string
来处理 toUpperCase
函数了。function toUpperCase(x: unknown) {
if(isString(x)) {
x.toUpperCase(); // ✅ all good, x is string
}
}
复制代码
is
让 ts 分辨了 unknown 类型和 更多的其他类型,但是也让我们类型缩小了范围。为什么啦?function pipsAreValid(pips: number) {
// we check for every discrete value, as number can
// be something between 1 and 2 as well.
return pips === 1 || pips === 2 || pips === 3 ||
pips === 4 || pips === 5 || pips === 6;
}
function evalThrow(count: number) {
if (pipsAreValid(count)) {
// my types are lying
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有