I have just started using Typescript. One problem I can't seem to solve without cheating the Typescript system and using any
type is the following:
I have 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())
})
})
},
I call elsewhere the following
let winningUser: UserDocument = await randomUser.saveExpirableToken(
'wonEverythingToken',
'wonEverythingTokenExpires',
moment().add(1, 'year').toDate() // add one year as expiration to claiming prize
)
The Typescript error I get is: Type 'void' is not assignable to type 'UserDocument'
What am I missing with my function declaration? And how do I handle Promises with Typescript such that I can tell Typescript that winningUser
will in fact 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'))
})
},
Please check out the type definition of this.save()
method, it seems like it does not return UserDocument
but instead returning void
.
I've created a playground link and it shows that your other type definitions is working just fine: Link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.