简体   繁体   English

TypeScript函数的返回类型中的关键字“is”

[英]The keyword “is” in the return type of TypeScript function

In VSCode's source file, there are some functions with a particular return type specification, like this: 在VSCode的源文件中,有一些具有特定返回类型规范的函数,如下所示:

export function isString(str: any): str is string {
  if (typeof (str) === _typeof.string || str instanceof String) {
    return true;
  }

  return false;
}

So I wonder what is the purpose of "str is string" instead of just writing "boolean". 所以我想知道“str is string”的目的是什么,而不仅仅是写“boolean”。

Can we use "str is string" and the like in any other circumstances? 我们可以在任何其他情况下使用“str is string”等吗?

That is called User-Defined Type Guards . 这称为用户定义类型保护

Regular type guards let you do this: 常规型护卫让你这样做:

function fn(obj: string | number) {
    if (typeof obj === "string") {
        console.log(obj.length); // obj is string here
    } else {
        console.log(obj); // obj is number here
    }
}

So you can use typeof or instanceof , but what about interfaces like this: 所以你可以使用typeofinstanceof ,但是这样的接口呢:

interface Point2D {
    x: number;
    y: number;
}

interface Point3D extends Point2D {
    z: number;
}

function isPoint2D(obj: any): obj is Point2D {
    return obj && typeof obj.x === "number" && typeof obj.y === "number";
}

function isPoint3D(obj: any): obj is Point2D {
    return isPoint2D(obj) && typeof (obj as any).z === "number";
}

function fn(point: Point2D | Point3D) {
    if (isPoint2D(point)) {
        // point is Point2D
    } else {
        // point is Point3D
    }
}

( code in playground ) 游乐场代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript中的泛型函数返回类型 - Generic return type of function in Typescript 函数声明的返回类型中的const关键字 - const keyword in return type of function declaration Typescript function 基于参数属性的返回类型 - Typescript function return type based on parameter properties 打字稿从参数返回函数类型 - Typescript return type of function from parameter TypeScript函数返回类型为null(如果参数为null) - Typescript function return type null if parameter null 函数返回类型和名称之间存在未知关键字 - unknown keyword present between function return type and name 在 typescript 中,如何使用泛型来约束和描述函数的返回值类型? - In typescript, How to use a generic to constraint and describe return value type of function? 为什么 typescript 不警告这个 function 中的返回类型? - Why doesn't typescript warn about the return type in this function? 如何根据 Typescript 的输入参数定义一个 function 的返回类型? - How to define the return type of a function according to the input parameters with Typescript? 在TypeScript中,我可以轻松键入命名箭头函数,但是如何在基于函数关键字的函数中执行相同的操作? - In TypeScript, I can easily type named arrow function, but how do I do the same thing in function keyword based function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM