The "is" keyword in the TypeScript function return type

There are some functions in the VSCode source file with a specific specification of the type of the return value, for example:

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".

Is it possible to use "str is string" and the like in any other circumstances?

+4
source share
1 answer

This is called User-Defined Type Guards .

Regulators of the usual type allow you to 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 typeofor instanceof, but what about these interfaces:

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
    }
}

( )

+5

Source: https://habr.com/ru/post/1662508/


All Articles