The term "is" in the output type of a TypeScript function

Within the source code of VSCode, you will find various functions that have a specific return type declaration, such as the following:

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

  return false;
}

This leads me to question the purpose of using "str is string" instead of simply stating "boolean."

Furthermore, can we apply the "str is string" pattern in other scenarios?

Answer №1

That technique is known as User-Defined Type Guards.

Standard type guards allow you to achieve the following:

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

While using typeof or instanceof, 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
    }
}

(playground link)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2- Techniques for exchanging data between isolated components

I am currently working on a project using Angular 2. Within this project, I have created two components: WorkspacesComponent and PagesComponent. In the database, each workspace contains a number of pages. I have written the code below to display the list ...

The implementation of race in React Redux Saga is proving to have negligible impact

I have implemented the following saga effect: function* loginSaga() { const logoutTimeoutCreationDate: string | null = yield localStorage.getItem('logoutTimeoutCreationDate'); let logoutTimeout: number; if (!logoutTimeoutCreationDate || + ...

Using both a 2D array and a vector of vectors as arguments in the template function

In the following code snippet: template <typename Edge, std::size_t N, typename Visitor> void report_edges(const Edge (&AdjacencyMatrix)[N][N], Visitor &&visitor) { for (std::size_t i = 0; i < N; ++i) { for (std::size_t j = ...

Ensure that an Enum is limited to only numerical values (implement type checks for Enum)

I am looking to enforce a Generic type to be strictly a numerical enum. This means that the values of the Enum should only be numbers. Here is an example: export type TNumberEnum<Enum> = { [key in keyof Enum]: number }; enum sample { AA, BB ...

The current version of Firebase functions is not reflecting the most recent modifications when running "firebase serve"

Exploring firebase functions has been a fun journey for me. Everything works smoothly when I deploy to the firebase server using the command firebase deploy --only functions. However, I wanted to test my functions locally before deploying them, and encount ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

Encountered an error while trying to update information in Angular

I have been working on a project involving a .NET Core Web API and Angular 11 (Full-Stack) project. I have successfully managed to add data to the database in my back-end, but I am encountering an issue when trying to update the data. Below is a snippet o ...

Issue with formatter function not being returned by Chartjs when using angular doughnut chart for displaying labels and values

Is it possible to display label names and values around the graph near the datasets segment? I have implemented a formatter function, but it is not returning the expected results. If you check my requirement here, you'll see what I'm aiming for. ...

What is the best way to send multiple values from the view to a method without using two-way binding?

https://i.sstatic.net/X4ivP.png When I change the dropdown value for the route type in my code, I need to pass both the gender value and the route type ID to my data retrieval method. Currently in my HTML file, I have only written a change event. I attem ...

Storing an email address in local storage using the Angular CLI

I'm currently working with Angular CLI and I want to save an email in Local Storage. Here is my HTML code: <input type="text" name="email_field" id="email"> <input type="submit" value="registration" onclick="save_email()"> Here is my Ty ...

Ways to verify function arguments within an asynchronous function using Jest

I have a function that needs to be tested export const executeCommand = async ( command: string ): Promise<{ output: string; error: string }> => { let output = ""; let error = ""; const options: exec.ExecOptions = { ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

An Easy Guide to Incorporating react-cookie into TypeScript Projects

I am currently developing an application in React using the React template provided by Visual Studio 2017. My goal is to incorporate react-cookie into my project. After installing this library with the command: npm install react-cookie However, when I at ...

Challenges arise when employing reduce with data types in an object

I want to transform an object in a function so that all keys are converted from Camel case to Pascal case. My Declaration: export interface INodeMailerResponseLower { accepted: string[]; rejected: string[]; envelopeTime: number; messageTim ...

Tips for managing a dblclick event on a row with data in a kendo-grid while using Angular2

Currently I am working with Angular2 and TS using kendo-grid. It allows me to access the data of the clicked row, but only for a singleClick event like so: (cellClick)="onCellClick($event.dataItem)". However, there is no direct way to achieve this for a d ...

Utilizing Angular and Typescript for Enhanced Modal Functionality: Implementing Bootstrap Modals in Various Components

When working in Angular, I have a component called Modal. I need to open the same Modal Component from two different places. The catch is, I want the button text in the Banner image to say "Get Started Now". Check out the Image linked below for reference. ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Typescript error when using fill or justify prop in React-bootstrap with Typescript

Code import { useCallback, useState, useEffect } from 'react'; import { Tabs, Tab, Spinner, Alert } from 'react-bootstrap'; import { Categories } from '../../models/ICategory'; import IMovie from '../../models/IMovie&apo ...

What steps can be taken to troubleshoot a TypeScript-powered Node.js application running in WebStorm?

Seeking advice on debugging a node.js application utilizing TypeScript within WebStorm - any tips? ...

Setting the default value for a useRef<HTMLInputElement> in ReactJs with Typescript

Is there a way to assign a number as the initial value on useRef<HTMLInputElement> without using useState<number>() since the field is a simple counter? Below is my TypeScript code: const MyComponent = () => { const productAmountRef = us ...