react-i18next: TS: Can no longer assign translations directly in a setState() after version 12.0.0 bump

šŸ› Bug Report

Prior to v12.0.0 we could assign our translation directly to a setState of the use state hook like so:

const [state, setState] = useState('');

function myFunction() {
 setState(t('my-translated-text'));
}

After the version bump from v11 to v12 we unfortunately face the below error: Argument of type 'DefaultTFuncReturn' is not assignable to parameter of type 'SetStateAction<string>'.

To Reproduce

image

Expected behavior

I would expect to be able to pass the TFunction directly to a setStateAction as in previous version.

We have found a workaround where can remove the error by wrapping the TFunction in a template string like so:

const [state, setState] = useState('');

function myFunction() {
 setState(`${t('my-translated-text')}`);
}

Is this now the intended way to pass translations to a setState hook after the latest type safety improvements? Please feel free to point me towards the new documentation about hook interaction in case I missed it.

Your Environment

  • runtime version: node v18
  • i18next version: 22.0.4
  • os: Mac

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 16 (9 by maintainers)

Most upvoted comments

t function can return null, this behaviour is set by default, if you want to change it, set returnNull type to false.

// i18next.d.ts
import 'i18next';

declare module 'i18next' {
  interface CustomTypeOptions {
    returnNull: false;
    ...
  }
}

I also recommend updating your i18next configuration to behave accordantly. https://www.i18next.com/overview/configuration-options#translation-defaults

i18next.init({
  returnNull: false,
   ...
});

should be fixed with i18next v22.0.5

This problem still occurs.

i18next 22.0.5 react-i18next 12.0.0

I bumped into the issue as well:

i18next 22.0.5
react-i18next 12.0.0

I followed the TypeScript definitions as well.

there are many related issues from people bumped to the version 22, so I’m surprised response is always the same 😃

Hey @MortenEmde, you need to either, include i18next.d.ts in the tsconfig.json file:

"include": [
    "./src/**/*",
    "./i18next.d.ts"
],

or move the i18next.d.ts to the src path.

https://codesandbox.io/s/i18next-translation-in-setstate-forked-iyhgch?file=/tsconfig.json:6-72