How to access the properties of a data that is defined with type "Object" in Typescript?

Asked

Viewed 70 times

1

I’m using a library jsonwebtoken, defining the type of return of a callback as object | undefined. I need to use this object to access a specific property, but I’m not getting it.

verify('', '', (err, data) => {
  if (err) {
    // Handle Error
    throw new Error(err);
  } 

  // Generate the new acessToken
  doSomething(data?.property) // Property doesn't exists on type object
  doSomething(data) // data is probably undefined 
});

I couldn’t figure out how to deal with this type of error. Below follows an excerpt from the definition of types from the library in question:

export type VerifyCallback = (
  err: VerifyErrors | null,
  decoded: object | undefined,
) => void;

1 answer

2


According to the types definition of the library you passed, the type of the second parameter of the callback is object | undefined.

This means that despite optional chaining (?.) allow you to "access" a property of an object that is possibly undefined, the guy object (defined by the library) does not say that there is a property property, you are trying to access. This is the cause of the error.

It means that you should provide a type to get rid of the error:

interface YourDecodedObject {
  property: string;
}

verify('foo', 'foo', (err, decoded: YourDecodedObject) => {
  if (err) {
    throw err;
  }

  console.log(decoded.property);
});

Another option would be to use type assertions.

In an ideal world, that function verify would accept a generic to type the second parameter of callback, but according to the definition you passed, this does not seem to be the case.

  • 1

    Thank you so much for the help. I was not yet aware of the assertions of type, I found quite useful for this case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.