-
-
Notifications
You must be signed in to change notification settings - Fork 337
Open
Labels
Description
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 MessageKeysDescribe 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);theoludwig