Enforcing return values with Typescript

  express, javascript, node.js, typescript

I have a class that has two methods for generating and decoding jsonwebtokens. This is what the class looks like.

interface IVerified {
  id: string
  email?: string
  data?: any
}

export default class TokenProvider implements ITokenProvider {
  public async generateToken({ id, email }: ITokenDetails): Promise<string> {
    return sign({ id, email }, CONFIG.JWT.secret, {
      subject: id,
      expiresIn: CONFIG.JWT.expires,
    })
  }
  

  public async decodeToken(token: string): Promise<IVerified> {
    const user = verify(token, CONFIG.JWT.secret)
    return user as IVerified
  }
}

In the decodeToken method, as you can see from above, it takes in a token and is meant to return the decoded values embedded in the token. But vscode Intellisense shows that jwt.verify() method returns a string | object. How can I override this to enforce the method to return some user attributes? Instead of getting string | object, I want to return the attributes described by the IVerified interface stated above. Any help is appreciated! Thank you very much.

Source: Ask Javascript Questions

LEAVE A COMMENT