is
is 可以缩小联合类型的类型推导。例子如下:
function isString(test: any): test is string{
return typeof test === 'string';
}
function example(foo: number | string){
if(isString(foo)){
console.log('it is a string' + foo);
console.log(foo.length); // string function
}
}
example('hello world');由于使用is 关键字,则能推导foo为string 类型。那么foo.length 就不会报错。
如果把test is string 改为boolean ,那么foo.length会直接报错
最后更新于
这有帮助吗?