2

I'm trying to compile a typescript file and it keeps throwing this error from the compiler: error TS2339: Property 'payload' does not exist on type 'string | object'. Property 'payload' does not exist on type 'string'.

Code in question:

decode(token: string): any {
  const decodedJWT = jwt.decode(token, { complete: true });

  const issuer = decodedJWT.payload.iss;
                           ^^^^^^^^^
  return {};
}

I'm using the @types/jsonwebtoken library to define the types. Any help would be much appreciated.

R.A. Lucas
  • 1,121
  • 1
  • 12
  • 17

1 Answers1

6

This error is caused by TypeScript type checking, the return type of jwt.decode() is null | object | string, if you're sure jwt.decode() always returns an object, you can cast decodedJWT to any type to avoid this error:

decode(token: string): any {
  const decodedJWT = jwt.decode(token, { complete: true });

  const issuer = (decodedJWT as any).payload.iss;
  return {};
}

In the above example, it might cause exception at runtime, because jwt.decode() might return null or a string, but only an object contains property payload, so you'd better handle the return value in a safer way:

decode(token: string): any {
  const decodedJWT = jwt.decode(token, { complete: true });

  if (decodedJWT === null) {
       // deal with null
  } else if (typeof decodedJWT === 'string') {
       // deal with string
  } else {
       const issuer = (decodedJWT as any).payload.iss; // cast to `any` type
  }

  return {};
}
kite.js.org
  • 1,599
  • 10
  • 11