【问题标题】:Typescript - translation strings typings solution?打字稿 - 翻译字符串打字解决方案?
【发布时间】:2021-08-21 12:37:27
【问题描述】:

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

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)。能做到吗?

【问题讨论】:

    标签: typescript types internationalization translation typescript-typings


    【解决方案1】:

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

    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
    

    Playground

    附:我的主要目标是使无效状态无法表示

    【讨论】:

    • 谢谢。在我的情况下,简单的trans: typeof Translations.cs | typeof Translations.en 就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2017-11-07
    • 2017-12-20
    • 2021-06-19
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多