Methods for handling various return types in Typescript

My code includes a method as shown below:

abstract canDeactivate() : boolean | Promise<boolean>;

I am seeking advice on how to handle both the promise and boolean implementations of this method in the caller's code.

Answer №1

To appropriately handle the two scenarios, you must implement a type guard:

abstract class Target {
    abstract canDeactivate(): boolean | Promise<boolean>;
}

declare let myTarget: Target;
const result = myTarget.canDeactivate();
if (typeof result === 'boolean') { // implementing a type guard
    result // this is a boolean value
} else {
    result.then(value => value) // result is of type Promise<bool>
}

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

Next.js Enhanced with Google Analytics

I've been experimenting with integrating Google Analytics into Next.js, following a tutorial on YouTube - https://www.youtube.com/watch?v=lMSBNBDjaH8 Following the instructions in the video, I added these two scripts in _document.js: <script async ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

WebStorm disregards tsconfig compiler directives when working with Angular applications

My project structure was created using angular-cli, which includes a root tsconfig.json, src/tsconfig.app.json, and src/tsconfig.spec.json. Despite having the noImplicitAny and strict options enabled in the root configuration, I do not receive error notifi ...

Obtain data based on the type of property

When examining the provided code snippet, I aim to filter properties based on their data type: interface Wrapper<T> { x: T; } interface WrapperOpt<T> { y?: T; } interface A { a1: number; a2: Wrapper<number>; a3: Wra ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

No recommended imports provided for React Testing Library within the VS Code environment

I am currently in the process of setting up a Next JS project with Typescript integration and utilizing React Testing Library. Unfortunately, I'm facing an issue with getting the recommended imports to work properly within my VS Code environment. To i ...

When the Angular Reactive form control does not show any errors, it is designated as ng-invalid

Currently, I am working on an (Angular 10) reactive form that includes multiple dynamically-created input components within an ngFor loop. Here is an example of one of these input components: <div [id]="this.getDivElementId()" class="text ...

TypeScript has two variable types

I'm facing a challenge with a function parameter that can accept either a string or an array of strings. The issue arises when trying to pass this parameter to a toaster service, which only accepts the string type. As a result, when using join(' ...

Error: The npm-link library encountered an invalid hook call

Problem Description: I am working on developing a package named eformless. To set up the package, I utilized CRA to create a directory named sandbox where I linked the package. However, I keep encountering an error when attempting to launch the sand ...

Guide on invoking personalized server-side functions (such as object parsing) utilizing Typescript and Angular tools

I've been grappling for weeks to make custom service calls function with Typescript / Angular / C#. It's been a challenge to find a workable solution online, and the more I search, the more bewildered I become. My current approach has largely be ...

Expanding MaterialUi styled components by incorporating TableCellProps: A guide

When trying to create a styled TableCell component in a separate file, I encountered an error in TypeScript (ts(2322)). TypeScript was indicating that the properties "component," "scope," and "colSpan" could not be used because they do not exist in StyledC ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

How can Material UI Textfield be configured to only accept a certain time format (hh:mm:ss)?

Looking for a way to customize my material ui textfield to allow input in the format of hh:mm:ss. I want to be able to adjust the numbers for hours, minutes, and seconds while keeping the colons automatic. Any suggestions would be welcomed. ...

What is the best way to generate documentation for the useState function using typedoc?

In my code, I have a documented hook that returns a state along with multiple functions. While the functions are well-documented in typedoc, the status in the final documentation is simply displayed as a boolean without any description. export default func ...

Error message on Cypress with TypeScript: No test specification files detected

Encountering the error "Unable to run because no spec files were found, even though there is a .ts spec file in Cypress. Execute the command below in the terminal: npx cypress run --spec="./cypress/integration/specs/Test1.spec.ts". Attempted to run the t ...

What could be causing my code to fail in retrieving lists from the SharePoint site?

I've been attempting to retrieve lists from a SharePoint site using the provided code, however, the list isn't appearing in the response. Could someone please offer assistance with this issue? I have tried various other solutions, but the problem ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

Verify enum values within controller function

I am dealing with a query parameter in my REST API that should be restricted to specific values according to an enum type. I need to find a way to handle a "Bad Request" error if the client provides any value outside of this enum. Here is what my enum loo ...

Error TS2339 occurs when the property "classes" is not found in the type "PropsWithChildren"

I have encountered a typescript error while transitioning our files to typescript. As a newcomer to typescript, it has been quite challenging for me to search for solutions online. My approach is to grasp the error first before delving into finding a resol ...

Error in GoogleMapReact with Next.js: TypeError occurs when trying to read properties of undefined, specifically 'getChildren'

Currently, I am working on a basic nextjs application using the google-map-react component and nextjs. However, I keep encountering an error whenever I try to utilize the component. The error message reads as follows: "TypeError: can't access propert ...