Search code examples
nestjsinternationalizationnestjs-i18n

I18nContext Error "Object is possibly undefined for I18nContext.current().lang


I am implementing nestjs-i18n in NestJs and I have done all the setup as per this official document

But in service, I am facing the error "Object is possibly undefined"

enter image description here

Here are my full-service codes:

import { Injectable } from "@nestjs/common";
import { I18nContext, I18nService } from "nestjs-i18n";

@Injectable()
export class FeaturedAgentsService {
  constructor(private readonly i18n: I18nService) {}
  async test(): Promise<any> {
    const message = this.i18n.t("lang.HELLO", {
      lang: I18nContext.current().lang,
    });
    return { service: message };
  }
}

Solution

  • After the exploration, I solve this by issue.

    The error Object is possibly 'undefined' arises because TypeScript is alerting to the potential of the I18nContext.current() function returning undefined. Accessing the lang property on an undefined value could lead to a runtime error.

    To resolve this error, I use optional chaining (?.) to safely access the lang property of I18nContext.current() without causing runtime errors.

    Here is the correct codes:

    import { Injectable } from "@nestjs/common";
    import { I18nContext, I18nService } from "nestjs-i18n";
    
    @Injectable()
    export class FeaturedAgentsService {
      constructor(private readonly i18n: I18nService) {}
      async test(): Promise<any> {
        const message = this.i18n.t("lang.HELLO", {
          lang: I18nContext.current()?.lang,  /***** Solved *****/
        });
        return { service: message };
      }
    }