fnando / i18n-js

It's a small library to provide the I18n translations on the Javascript. It comes with Rails support.
MIT License
3.77k stars 520 forks source link

Bug: scope and options should be read-only #689

Closed trajano closed 1 year ago

trajano commented 1 year ago

Description

I am looking for the code so I can PR but I can't seem to find it.

Anyway ...

t: <T = string>(scope: Scope, options?: TranslateOptions) => string | T;

Should be

t: <T = string>(scope: ReadOnly<Scope>, options?: TranslateOptions) => string | T;

This will allow us to have a construct

t`mykey`

Which is being prevented by typescript because Scope's array form is mutable.

  /**
   * Translator function.  
   * @param scope
   * @param options
   */
  t(scope: Readonly<Scope>, options?: TranslateOptions) : string;
trajano commented 1 year ago

What I did was create a wrapper as well

  const t = useCallback(
    (scope: Scope, options?: TranslateOptions) => {
      // this conditional allows for the short form.
      if (Array.isArray(scope)) {
        return i18n.t(
          scope.filter((p) => p.length > 0),
          options
        );
      } else {
        return i18n.t(scope, options);
      }
    },
    [i18n, locale]
  );

This allows for something like

const loginButtonText = useMemo(() => username.length > 0 ? t`loginAs${{ username }}` : t`login`, [t, username])

The filter was needed because

t`loginAs${{ username }}` 

translates to add an empty string.

t ( ["loginAs", ""], { username })
fnando commented 1 year ago

I don't want to explicitly add support to templated strings as it's too complicated. I think creating a wrapper, as you did, is the way to go.

trajano commented 1 year ago

You don't have to create an explicit support for it, but the more correct typing is to make it ReadOnly

trajano commented 1 year ago

Ah okay so the JS code is in https://github.com/fnando/i18n

fnando commented 1 year ago

It's all good. I don't mind handling those issues here as well. :)

trajano commented 1 year ago

I was trying to figure out where the JS code was since I couldn't find it in this repo (with the -js suffix)

fnando commented 1 year ago

There's history there. i18n-js repo used to have both Rails/Ruby code and the JS code. I broke both apart but didn't want to get riddle of the history of this repo, so in short, it's a mess. hahahaha