常用于函数的返回值,判断类型是否是某种类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function isString(test: any): test is string { return typeof test === 'string' }
function example(foo: any) { if (isString(foo)) { console.log('it is a string' + foo) console.log(foo.length) } else { console.log('not string') } } example('hello world') example(2)
|
is关键字只会在判断后的块级作用域中生效
E.g.2
1 2 3 4 5 6 7 8
| function example(foo: any) { if (isString(foo)) { console.log('it is a string' + foo) console.log(foo.length) } console.log(foo.toExponential(2)) }
|
这说明,is关键字,只会在判断后的块作用域中生效,所以离开了作用域的foo在ts编译器中又变回any类型