Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any
type:
The issue arises with a function that returns a promise:
saveExpirableToken(tokenField: string, tokenExpiresField: string, tokenExpiresAt: Date) {
return new Promise<UserDocument>((resolve, reject) => {
this.generateResetToken((err: Error, resetToken: string) => {
if (err) { reject(err) }
this[tokenField] = resetToken
this[tokenExpiresField] = tokenExpiresAt
resolve(this.save())
})
})
},
When I try to call this function elsewhere like so:
let winningUser: UserDocument = await randomUser.saveExpirableToken(
'wonEverythingToken',
'wonEverythingTokenExpires',
moment().add(1, 'year').toDate() // add one year as expiration to claiming prize
)
An error in Typescript shows up saying:
Type 'void' is not assignable to type 'UserDocument'
I'm puzzled about what's causing this error in my function declaration. How can I properly handle Promises in Typescript and assure Typescript that winningUser
will indeed be of type UserDocument
** Edit **
generateResetToken(callback: (err: Error | null, token?: string) => Promise<UserDocument>) {
const byteSize = 16
crypto.randomBytes(byteSize, (err, resetToken) => {
if (err) { callback(err) }
callback(null, resetToken.toString('hex'))
})
},