TypeScript中的类型谓词is

431 阅读1分钟

TypeScript里有类型保护机制。要定义一个类型保护,我们只要简单地定义一个函数,它的返回值是一个类型谓词:

function isString(test: any): **test is** **string**{
    return typeof test === "string";
}
// test -> 形参名
// is -> 关键字
// string -> 类型
function isString(test: any): boolean{
    return typeof test === "string";
}

上面两种写法区别在哪里呢?

区别

  • 使用 is 类型保护
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); // string function
        // 如下代码**编译时会出错,运行时也会出错**,因为 foo 是 string 不存在toFixed方法
        console.log(foo.toFixed(2));
    }
    // 编译不会出错,但是运行时出错
    console.log(foo.toFixed(2));
}
example("hello world");
  • 使用返回值为boolean
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); // string function
        // 如下代码**编译时不会出错,运行时会出错**,因为 foo 是 string 不存在toFixed方法
        console.log(foo.toFixed(2));
    }
    // **编译不会出错,但是运行时出错**
    console.log(foo.toFixed(2));
}
example("hello world");

总结:

  • 在使用类型保护时,TS 会进一步缩小变量的类型。例子中,将类型从 any 缩小至了 string
  • 类型保护的作用域仅仅在 if 后的块级作用域中生效