Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  91] [ 7]  / answers: 1 / hits: 79360  / 7 Years ago, sun, august 13, 2017, 12:00:00

I'm trying to return a boolean after a promise resolves but typescript gives an error saying



A 'get' accessor must return a value.



my code looks like.



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 code is for Ionic 3 Application and the storage is Ionic Storage instance.


More From » typescript

 Answers
24

You can return a Promise that resolves to a boolean like this:



get tokenValid(): Promise<boolean> {
// |
// |----- Note this additional return statement.
// v
return this.storage.get('expires_at')
.then((expiresAt) => {
return Date.now() < expiresAt;
})
.catch((err) => {
return false;
});
}


The code in your question only has two return statements: one inside the Promise's then handler and one inside its catch handler. We added a third return statement inside the tokenValid() accessor, because the accessor needs to return something too.



Here is a working example in the TypeScript playground:



class StorageManager { 

// stub out storage for the demo
private storage = {
get: (prop: string): Promise<any> => {
return Promise.resolve(Date.now() + 86400000);
}
};

get tokenValid(): Promise<boolean> {
return this.storage.get('expires_at')
.then((expiresAt) => {
return Date.now() < expiresAt;
})
.catch((err) => {
return false;
});
}
}

const manager = new StorageManager();
manager.tokenValid.then((result) => {
window.alert(result); // true
});

[#56780] Thursday, August 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sandra

Total Points: 708
Total Questions: 100
Total Answers: 84

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;