i18next“t”变量的类型是什么(TYPESCRIPT)

问题描述 投票:0回答:4

我使用 i18next,我想将 t 函数 prop 传递到我的界面。

经验:

const { t } = useTranslation();

export interface ITranslate {
   translate: ... type?
}

“t”变量的类型是什么?

reactjs react-native i18next
4个回答
7
投票

也许这会起作用:

import { TFunction } from "react-i18next";

export interface ITranslate {
   translate: TFunction
}

4
投票

最好的方法就是使用

t: typeof i18next.t

在这种情况下,如果您还对翻译文件使用

<const>
运算符,它将保护翻译功能中的输入,而
TFunction
则不会。

<const>
翻译用法示例:

# translations.ts file

import en from "./en.json"
import fr from "./fr.json"
import cz from "./cz.json"

export default <const>{
  en,
  fr,
  cz
}    

# i18next.d.ts file
    
    import translations from "./translations"
    
    declare module "i18next" {
      interface CustomTypeOptions {
        defaltNS: 'en',
        resources: typeof translations["en"]
      }
    }

这样您将在想象的应用程序中得到以下结果:

# en.json file
{
  "first": "This is first",
  "second": "This is second"
}

# Component.tsx file
import i18next from "18next";

const shouldWork = i18next.t('first')
const shouldFail = i18next.t('third') // TS will show an error

确保

"resolveJsonModule": true
文件中有
tsconfig.json


1
投票

您可以使用

ReturnType
实用程序类型:

export interface ITranslate {
   translate: ReturnType<typeof useTranslation>['t']
}

0
投票

这两个答案都不适合我在react + TS项目上使用当前最新版本的i18n(23.10.1)。 在导入中添加

type
修复了所有问题。

import type { TFunction } from "i18next";

© www.soinside.com 2019 - 2024. All rights reserved.