Home > Software design >  Object 'err' is of type unknown
Object 'err' is of type unknown

Time:09-23

So I am looking at some code for a backend and I noticed anywhere that a method has async in front of it, inside the try/catch statement TypeScript complains about the err object, saying Object 'err' is unknown, but that does not occur for methods that are synchronous.

async createOrganization(dbSession: ClientSession, organization: IOrganization): Promise<IOrganization> {
    try {
      // @ts-ignore
      const newOrganization = new this.Model(organization)
      // @ts-ignore
      await newOrganization.save()
      // @ts-ignore
      return newOrganization
    } catch (err) {
      throw new OrganizationCreationError(err.message)
    }
  }

What is it about utilizing the try/catch inside an asynchronous method that makes that err object be unknown and how can I fix it?

CodePudding user response:

The catch clause variable was historically typed as any, but since TypeScript 4.4 under the strict compiler option (or the new useUnknownInCatchVariables option) it is now typed as unknown. It has nothing to do with methods being anynchronous.

If you aren't seeing this error in some other parts of your codebase that fall under the same TypeScript version and compiler options, a few possible reasons come to mind:

  • The catch clause variable isn't being used in a way incompatible with the unknown type, perhaps it's being passed to a function that accepts an unknown or any typed parameter.
  • The catch clause variable is explicitly typed as any.
  • Related