"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

What is the most efficient method for line wrapping in the react className attribute while utilizing Tailwind CSS with minimal impact on performance?

Is there a more efficient way to structure the className attribute when utilizing tailwind css? Which of the examples provided would have the least impact on performance? If I were to use an array for the classes and then join them together as shown in e ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Mastering the art of accessing properties in typescript post implementing Object.defineProperty

I was experimenting with the TypeScript playground trying to figure out decorators and encountered some questions. class PathInfo { functionName: string; httpPath: string; httpMethod: string; constructor(functionName: string, httpPath: str ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

Is it possible to send an AJAX request to a Django view that might result in a redirect?

Query I encountered an issue while attempting to access a specific Django view through AJAX. This particular view redirects users if they haven't authorized the site with Google. I suspect the problem arises from redirecting "within" a view requested ...

How do I implement a dynamic input field in Angular 9 to retrieve data from a list or array?

I'm looking to extract all the strings from the Assignes array, which is a property of the Atm object, and populate dynamic input fields with each string. Users should be able to update or delete these strings individually. What approach can I take us ...

The Ajax form's malfunction is attributed to JSON, as it throws a parser error indicating a SyntaxError. Specifically, the JSON.parse function encounters an unexpected end of data at line 1, column 1

I understand that this is a commonly asked question, but I have tried all the solutions provided and none of them have worked for me. My specific issue is that I am unable to load a JSON response from the server using AJAX. Here's the setup: my "scrip ...

How can you utilize a previously opened window from another page in JavaScript?

One of my challenges involves managing windows in a JavaScript environment. When I open a child window using window.open("http://foobar","name"), it reuses the same window when opened with the same name, which is exactly what I want. However, if the origi ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Retrieving the `top` value using `$this.css("top") can either return an object or an element value

Something odd is happening with my HTML object: <div data-x="1" data-y="1" class="tile empty" style="top: 32px; left: 434px;"> <div class="inner">1:1</div> </div> When attempting to access its top property in jQuery using the ...

Exploring the contrast between string enums and string literal types in TypeScript

If I want to restrict the content of myKey in an object like { myKey: '' } to only include either foo, bar, or baz, there are two possible approaches. // Using a String Literal Type type MyKeyType = 'foo' | 'bar' | &ap ...

What improvements can I make to enhance my method?

I have a block of code that I'm looking to clean up and streamline for better efficiency. My main goal is to remove the multiple return statements within the method. Any suggestions on how I might refactor this code? Are there any design patterns th ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

Enhancing Functional Components with Idle Timeout using React Hooks

I am currently working on an application that requires implementing an idle timeout feature. This feature should first notify the user that they will be logged out in one minute, and then proceed to log them out after the time has expired. Previously, I s ...

Another approach to utilize JavaScript for populating content into a <div> container?

Upon loading the page, I aim to display a message in the <div> element. Below is the HTML and JavaScript code I have implemented: <body onload="printMsg()"> <div id="write"></div> </body> function printMsg() { var no ...

Obtaining the attribute value from a custom tag in Angular: A comprehensive guide

I am currently working on creating a customized password component in Angular5. I am having difficulty obtaining the minimum and maximum attribute values required to validate the password. I attempted to retrieve the values using JavaScript's getAttr ...