typescript - 打字稿 - 翻译字符串打字解决方案?
问题描述
我正在使用这种对象格式来存储多种语言的翻译字符串:
export const Translations = {
'en': {
text1: 'Hello world!',
text2: 'Login'
}
'cs': {
text1: 'Ahoj svět!',
text2: 'Přihlášení'
}
}
然后我有我的状态和定义的状态接口:
export const MyState: State = {
lang: 'cs',
trans: Translations.cs,
}
export type State = {
lang: LangCodes,
trans: ???
}
现在我需要以某种方式定义它MyState.trans
只能包含翻译属性的名称,这意味着text1, text2
在这种情况下。启用类型检查的东西会在编辑器中为此对象的自动完成功能(当像这样使用时:)MyState.trans.text1
。可以做到吗?
解决方案
我相信所有可能/允许状态的联合应该有助于:
export const Translations = {
'en': {
text1: 'Hello world!',
text2: 'Login'
},
'cs': {
text1: 'Ahoj svět!',
text2: 'Přihlášení'
}
} as const
type Translations = typeof Translations
type LangCodes = keyof Translations
type Values<T> = T[keyof T]
// Make union of all allowed states
type Union = {
[P in LangCodes]: {
lang: P,
trans: Translations[P]
}
}
// get all values of the union
type State = Values<Union>
export const MyState: State = {
lang: 'cs',
trans:Translations.cs
} // ok
export const MyWrongState: State = {
lang: 'cs',
trans:Translations.en
} // error
PS我的主要目标是使无效状态无法表示
推荐阅读
- docker - Docker:由于缺少 bash,无法编辑图像中的代码
- apache-kafka - KSQL query not returning the response via REST API , even I am using LIMIT clause
- c++ - 从另一个类更改一个类的数据成员的值
- spring-boot - findBy 不使用继承的属性
- c# - NLog中的顺序文件名
- sql - 使用过滤器查询大表与数据库中的小表 - 任何性能提升?
- typescript - 如何使用道具修复此错误(ReactNative + Typescript)
- vbscript - Server.URLEncode 开始用加号(“+”)而不是百分比-20(“%20”)替换空白
- python - 在 Chaquopy 中转换数组和张量
- c# - MySqlConnection ignores incorrect password when SQL username matches Windows account