类型谓词 is
function isNumber(x: any): x is number {
return typeof x === "number";
}
function isString(x: any): x is string {
return typeof x === "string";
}
类型谓词 is
function isNumber(x: any): x is number {
return typeof x === "number";
}
function isString(x: any): x is string {
return typeof x === "string";
}
类型谓词的函数,输出一个布尔值,如果返回true,所输入的参数x 就是 is后面对应的类型。 通常用在给联合类型确定一个具体的类型。
比如:
type num_str = number | string ;
let a : num_str;
// ..... 过了若干操作后,无法确定a是什么类型
//然后
function isNumber(x: any): x is number {
return typeof x === "number";
}
if(isNumber(a)){
let b = 100 - a; //语句块里, tsc 会把a 分析为 number
}
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
https://segmentfault.com/a/11...