首页 > 解决方案 > 打字稿 - 翻译字符串打字解决方案?

问题描述

我正在使用这种对象格式来存储多种语言的翻译字符串:

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。可以做到吗?

标签: typescripttypesinternationalizationtranslationtypescript-typings

解决方案


我相信所有可能/允许状态的联合应该有助于:

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我的主要目标是使无效状态无法表示


推荐阅读