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

Ron*_*ong 4 function typescript

在VSCode的源文件中,有一些具有特定返回类型规范的函数,如下所示:

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

  return false;
}
Run Code Online (Sandbox Code Playgroud)

所以我想知道"str is string"的目的是什么,而不仅仅是写"boolean".

我们可以在任何其他情况下使用"str is string"等吗?

Nit*_*mer 5

这被称为用户定义类型保护.

常规型护卫让你这样做:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以使用typeof或者instanceof,但是这样的接口呢:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

(游乐场代码)

  • 这是一个错字吗?`函数 isPoint3D(obj:any): obj 是 Point2D`。不应该是“obj is Point3D”吗? (2认同)