typescript - `is` 关键字在 typescript 中有什么作用?

标签 typescript keyword

我遇到了一些看起来像这样的代码:

export function foo(arg: string): arg is MyType {
    return ...
}

我无法在文档或谷歌中搜索到 is,这是一个很常见的词,基本上每个页面都会出现。

关键字在该上下文中的作用是什么?

最佳答案

参见 user-defined type guard functions 的引用资料获取更多信息。

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
    }
}
example("hello world");

isString() 之后,在上述格式中使用类型谓词 test is string(而不是仅仅使用 boolean 作为返回类型) > 被调用时,如果该函数返回 trueTypeScript 会将类型缩小为 string 在任何由函数调用保护的 block 中。 编译器会认为 foo 是 below-guarded block 中的 string(并且仅在 below-guarded block 中)

{
    console.log("it is a string" + foo);
    console.log(foo.length); // string function
}

类型谓词仅在编译时使用。生成的 .js 文件(运行时)将没有区别,因为它不考虑 TYPE。

我将通过以下四个示例来说明差异。

例如 1: 上面的示例代码不会有编译错误和运行时错误。

例如 2: 下面的示例代码将出现编译错误(以及运行时错误),因为 TypeScript 已将类型缩小为 string 并检查 toExponential 不属于 字符串方法。

function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length);
        console.log(foo.toExponential(2));
    }
}

例如3: 下面的示例代码没有编译错误,但会出现运行时错误,因为 TypeScript 只会在 protected block 中将类型缩小为 string 而不是之后,因此 foo.toExponential 不会产生编译错误(TypeScript 不认为它是 string 类型)。但是在运行时,string没有toExponential方法,所以会出现运行时错误。

function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length);
    }
    console.log(foo.toExponential(2));
}

例如4: 如果我们不使用 test is string(类型谓词),TypeScript 将不会缩小 protected block 中的类型,下面的示例代码不会出现编译错误,但会出现运行时错误。

function isString(test: any): boolean{
    return typeof test === "string";
}
function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length);
        console.log(foo.toExponential(2));
    }
}

结论是 test is string (type predicate) 在编译时用来告诉开发者代码将有机会出现运行时错误。对于 javascript,开发人员不会知道编译时的错误。这是使用 TypeScript 的优势。

关于typescript - `is` 关键字在 typescript 中有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081332/

相关文章:

java - 新关键字的副作用

typescript - 如何使用 ionic 2/angular 2 和 typescript 设置 firebase

node.js - 得到错误 TS2304 : Cannot find name 'Buffer'

java - java中使用关键字输出句子

javascript - var 关键字的用途是什么以及何时应该使用它(或省略它)?

c - "code"在这种情况下是什么意思?

html - 如何使用 Angular 6 向表格添加附加功能

reactjs - 如何更改 NextJS 13 中服务器操作的状态?

angular - 带有 AOT 的延迟加载模块 - TypeError : '' is not a function when served from NGINX

c - main 和 fopen 是有效的变量名吗?