Ele*_*epi 5 typescript i18next react-i18next
i18next v22.0.0为翻译功能提供了完整的类型安全性t('world.greeting'),这非常棒。但由于您可以使用该t()函数从嵌套翻译中检索对象,因此它可能会返回一个对象或字符串。
我总是将结果传递给字符串的翻译键。我主要在必须返回字符串的上下文中使用t(),因此以下代码片段中的函数会产生 TypeScript 错误:
const resources = {
en: {
translation: {
world: {
withGreeting: 'Hello World',
withoutGreeting: 'World',
someNestedProperty: {
hello: 'Text',
}
},
},
},
}
// Declare i18next typings: https://www.i18next.com/overview/typescript
declare module "i18next" {
interface CustomTypeOptions {
resources: typeof resources["en"];
}
}
// (...) initialize i18next
const getText = (enabled: boolean): string => {
if(enabled) {
// Typescript Error: string | { hello: string } not assignable to type string
return t('world.withGreeting');
}
return t('world.withoutGreeting');
}
Run Code Online (Sandbox Code Playgroud)
是否有可能使用一些 TypeScript 魔法来强制t()只返回一个字符串?
| 归档时间: |
|
| 查看次数: |
1324 次 |
| 最近记录: |