Reputation: 9251
Typescript is failing to transpile my code as it believes the objects method doesn't exist.
At run time, when the promise has resolved, the method does exists. It just doesn't exist at the time the typescript is trying to transpile because the Promise is returned.
My function that returns the promise which resolves the oauthclient:
public generateOauthClient(){
return new Promise((resolve, reject) => {
// Load client secrets from a local file.
fs.readFile(appConfig.youtube.keyFilename, 'utf8', function processClientSecrets(err, content) {
if(err) {
return reject('Error loading client secret file: ' + err);
}
const credentials = JSON.parse(content);
const clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const auth = new googleAuth();
const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
resolve(oauth2Client);
})
});
}
And then I try call that elsewhere in my code
const oauth2Client = await this.generateOauthClient();
oauth2Client.setCredentials({
access_token: JSON.parse(tokens).access_token,
refresh_token: JSON.parse(tokens).refresh_token
});
oauth2Client.refreshAccessToken((err, tokens) => {
if(err) return reject(err)
this.storeToken(tokens).then(()=>{
resolve('Successfully updated tokens')
}).catch((err2)=> {
reject(err2)
})
});
Then I get the typescript error: Property 'setCredentials' does not exist on type '{}'
If I change my generateOauthClient
function to return a callback as opposed to returning a promise, typescript transpiles fine.
How do I get around this so I can use promises instead of callbacks?
Upvotes: 0
Views: 239
Reputation: 249756
You need to tell Typescript what your Promise
will return. This will allow Typescript to check what you do with the result in either syntax you use (async/await or .then):
new Promise<auth.OAuth2>((resolve, reject) => { .. } )
Upvotes: 1