随笔

as is

  1. as 是类型断言
let someValue: any = 'this is a string'

let strLength: number = (someValue as string).length
  1. 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 为关键字的「类型谓语」把参数的类型范围缩小了,当使用了 test is string 之后,我们通过 isString(foo) === true 明确知道其中的参数是 string,而 boolean 并没有这个能力,这就是 is 关键字存在的意义.

posted @ 2021-11-10 13:18  webLion200  阅读(11)  评论(0编辑  收藏  举报