"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says:

A 'get' accessor must return a value.

The code snippet causing the issue is as follows:

get tokenValid(): boolean {
    // Check if current time is past access token's expiration
    this.storage.get('expires_at').then((expiresAt) => {
      return Date.now() < expiresAt;
    }).catch((err) => { return false });
}

This particular piece of code pertains to an Ionic 3 Application with the storage being an instance of Ionic Storage.

Answer №1

To check if a token is valid, you can create a function that returns a Promise which resolves to a boolean value as shown below:

verifyTokenValidity(): Promise<boolean> {
  // |
  // |----- Make sure to include the return statement here 
  // v
  return this.storage.fetch('token_expiry')
    .then((expiryTime) => {
      return Date.now() < expiryTime;
    })
    .catch((error) => {
      return false;
    });
}

In the provided code snippet, there are three return statements included: one within the 'then' block of the Promise, another in the 'catch' block, and finally inside the 'verifyTokenValidity()' method itself. It's crucial for the accessor method to also have a return statement.

If you want to see this implementation in action, you can experiment with it here in the TypeScript playground:

class StorageHandler { 

  // Mocking storage for demonstration
  private storage = {
    fetch: (key: string): Promise<any> => { 
      return Promise.resolve(Date.now() + 86400000);
    }
  };

  verifyTokenValidity(): Promise<boolean> {
    return this.storage.fetch('token_expiry')
      .then((expiryTime) => {
        return Date.now() < expiryTime;
      })
      .catch((error) => {
        return false;
      });
  }
}

const handler = new StorageHandler();
handler.verifyTokenValidity().then((isValid) => { 
  console.log(isValid); // true
});

Answer №2

Make sure your function looks like this:

const checkTokenValidity = async () => {
    try {
        const expiresAt = await getExpirationDate();
        return Date.now() < expiresAt;
    } catch (error) {
        console.error(error);
        return false;
    }
};

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

Tips for preventing line breaks within table cells

Looking at the image below, I need to display the Hallticket in a single line. The first one is retrieved directly from the database, while the second one is added dynamically using JavaScript. How can I show both sets of data in a single line? <td&g ...

What is the recommended TypeScript type for the NextJS _app.tsx Component and pageProps?

Take a look at the default _app.tsx code snippet from NextJS: function MyApp({ Component, pageProps }) { return ( <Component {...pageProps} /> ) } The issue arises when transitioning to TypeScript, as ES6Lint generates a warning indicating t ...

Concealing HTML pages in Node.js: A step-by-step guide

I have a specific requirement where my website's html pages should only be accessible to users who are logged in. However, when I used the command below, my html pages became public: app.use(express.static('public')); For instance, I do no ...

"An issue with preventing default behavior when clicking on a jQuery element

I need some assistance preventing a JQuery onclick function from scrolling the page to the top. I have tried using preventDefault() without success. You can find the code on this website: Below is the code snippet that I am currently using: $( document ...

The JSON response did not contain the expected property in Javascript

Currently, I am developing a weather widget using React that displays temperature and rain forecast. The data is fetched from OpenWeather API and the JSON response structure is as follows: //rainy day 0:{ main: { temp:10} rain: { 3h: 1000} } / ...

When a button is clicked, load two separate pages into two distinct divs at the same time

$('#menuhome').click(function(){ $('#leftcolumncontainer').load('pages/homemenu.php'); }); the code above is used to load the home menu on the left side. Now, let's add the following: $('#menu ...

What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN. I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it sh ...

Troubles encountered when trying to execute mocha within Firebase functions

My latest project involved developing a Node/Typescript app that interacted with data from Firebase Cloud Firestore. The app performed flawlessly, and I conducted endpoint testing using simple mocha commands on the generated .js file. Below is an example o ...

Utilizing the useEffect hook to display a notification banner when a message is present, along with implementing useState for managing the state of that message

I created a component that displays a Snackbar if a message is not null. I implemented it to show up when someone clicks on the Log In button, and if there is an error, the error message should be displayed in the Snackbar. However, once the user closes th ...

Utilizing React for handling data exchange between child and parent components

I am still learning about React and material-ui, and I am exploring how to pass data from a child component to a parent component to update the parent state. Currently, when I try to update the state with a new date, it is being logged in the console but t ...

Using Nestjs to inject providers into new instances of objects created using the "new" keyword

Is it possible to inject a provider into objects created by using the new keyword? For instance: @Injectable() export class SomeService { } export class SomeObject { @Inject() service: SomeService; } let obj = new SomeObject(); When I try this in my t ...

Use the ngFor directive to iterate over the most recently created array from the parent ng

I am looking to link material tabs with ngFor to generate arrays for child ngFor. Let's start from the beginning: <mat-tab-group> <mat-tab *ngFor="let tab of asyncTabs "> <ng-template mat-tab-label>{{tab.label}}</ng-template ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

Retrieving the body of a GET request using NodeJS and axios

Let me share my request with you: axios.get(BASE_URI + '/birds/random', {Stuff: "STUFF"}) .then(randBird=>{ const birdData = randBird.data const bird = { age: birdData.age, ...

The seamless union of Vuestic with Typescript

Seeking advice on integrating Typescript into a Vuestic project as a newcomer to Vue and Vuestic. How can I achieve this successfully? Successfully set up a new project using Vuestic CLI with the following commands: vuestic testproj npm install & ...

Looking to display several charts on a single page with varying datasets?

I have successfully integrated a doughnut chart plugin into my website. However, I would like to display multiple charts on the same page with different data sets. Below is the code snippet for the current chart being used: This is the chart I am using & ...

Using Vue.js causes an issue with Array.from(Object).forEach

When using vue.js 2 CLI, I typically define object data like this within the data() function: data(){ return{ user: { user_mail: '', user_password: '', user_confirm_password : '' ...

How to toggle the visibility of specific div elements within a v-for loop depending on their content?

I am working on a scenario where I have a collection of objects displayed in a v-for loop. Each object has a specific key value pair, and I want the user to be able to toggle a button outside the loop to show or hide elements based on that key value. Initi ...

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...

Looking for assistance in using JavaScript to determine the percentage of a DIV's width in pixels

Using PHP, I am generating boxes whose width is set to 100% of a container in CSS. Now, I want to determine the equivalent pixel value of that box... HTML <div class="masonry" > <? while($row = $stmt->fetch()){ ?> <div class="i ...