Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

Can we use "str is string" and the like in any other circumstances?

like image 401
Rong Avatar asked Dec 01 '16 08:12

Rong


People also ask

What is return type function in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

What is keyword type in TypeScript?

In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types.

Is there a function type in TypeScript?

Types of Functions in TypeScript: There are two types of functions in TypeScript: Named Function. Anonymous Function.


1 Answers

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:

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)

like image 117
Nitzan Tomer Avatar answered Oct 30 '22 07:10

Nitzan Tomer