TypeScript函数返回类型中的关键字"is"的含义是什么?

10

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

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

  return false;
}

我想知道“str is string”的目的是什么,而不只是写成“boolean”。

我们可以在其他情况下使用“str is string”之类的吗?

1个回答

13
那被称为用户自定义类型保护
常规类型保护允许你这样做:
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
    }
}

所以你可以使用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
    }
}

在游乐场中的代码

2
这是一个打字错误吗?function isPoint3D(obj: any): obj is Point2D。难道不应该是obj is Point3D吗? - Oygen87

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接