Skip to content

t.has should act as a type guard #2104

@G07cha

Description

@G07cha

Is your feature request related to a problem? Please describe.

When getting translations from useTranslations hook via keys of broad or unknown type in Typescript, it's highly likely to run into an issue that the key cannot be used unless its type is narrowed down to IntlMessages keys. There is a helpful t.has method that checks if the given key exists, but as it only accepts IntlMessages keys and returns boolean, hence the variable needs to be cast twice:

const t = useTranslations();
const key: string = 'foo';

// Error - Argument of type 'string' is not assignable to parameter of type MessageKeys...
if (t.has(key)) {
  // Error - Argument of type 'string' is not assignable to parameter of type MessageKeys...
  return t(key);
}

Describe the solution you'd like

t.has can accept a broader type (string perhaps?) and act as a type guard:

function has(key: string): key is keyof MessageKeys

Describe alternatives you've considered

Right now, I've written the following wrapper to achieve it:

export const hasTranslation = <TranslateFn extends ReturnType<typeof useTranslations>>(
  t: TranslateFn,
  key: string
): key is Parameters<typeof t>[0] => t.has(key as any);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions